有没有办法在 C# 4.0 中使用匹配中包含的文本函数进行正则表达式替换?
在php中有这样的东西:
reg_replace('hello world yay','(?=')\s(?=')', randomfunction('$0'));
它为每场比赛提供独立的结果,并在找到每场比赛的地方替换它。
See the Regex.Replace方法有一个MatchEvaluator
超载。这MatchEvaluator
是一种方法,您可以指定该方法来处理每个单独的匹配项并返回应用作该匹配项的替换文本的内容。
例如,这个...
猫跳过了狗。
0:THE 1:CAT 跳过 2:THE 3:DOG。
...是以下内容的输出:
using System;
using System.Text.RegularExpressions;
namespace MatchEvaluatorTest
{
class Program
{
static void Main(string[] args)
{
string text = "The cat jumped over the dog.";
Console.WriteLine(text);
Console.WriteLine(Transform(text));
}
static string Transform(string text)
{
int matchNumber = 0;
return Regex.Replace(
text,
@"\b\w{3}\b",
m => Replacement(m.Captures[0].Value, matchNumber++)
);
}
static string Replacement(string s, int i)
{
return string.Format("{0}:{1}", i, s.ToUpper());
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)