在C# 4.0中是否有一种方法可以使用匹配文本中的函数进行正则表达式替换?
在php中有类似以下的做法:
reg_replace('hello world yay','(?=')\s(?=')', randomfunction('$0'));
它为每个匹配提供独立的结果,并在找到每个匹配项时进行替换。
查看具有 MatchEvaluator
重载的 Regex.Replace
方法。 MatchEvaluator
是一个方法,您可以指定它来处理每个单独的匹配,并返回应用于该匹配的替换文本。
例如,下面的代码会输出:
The cat jumped over the dog.
0:THE 1:CAT jumped over 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());
}
}
}