有没有办法在正则表达式中执行动态替换?

有没有办法在C#4.0中使用匹配中包含的文本函数进行正则表达式替换?

在PHP中有这样的东西:

reg_replace('hello world yay','(?=')\s(?=')', randomfunction('$0')); 

并且它为每个匹配提供独立的结果,并在找到每个匹配的地方替换它。

请参阅具有MatchEvaluator重载的Regex.Replace方法。 MatchEvaluator是一种方法,您可以指定该方法来处理每个匹配项,并返回应该用作该匹配项的替换文本的方法。

例如,这……

那只猫跳过了狗。
0:1:CAT跳过2: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()); } } }