2011-04-07 20 views
9

有沒有辦法在C#4.0中使用匹配中包含的文本的函數進行正則表達式替換?有沒有辦法在正則表達式中執行動態替換?

在PHP中有這樣的事情:

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

,並讓獨立計算的結果每場比賽和替換它,每個找到匹配。

回答

9

請參閱有MatchEvaluator過載的Regex.Replace方法。 MatchEvaluator是您可以指定的方法來處理每個單獨的匹配,並返回應該用作該匹配的替換文本的內容。

例如,這...

貓跳過了狗。
0:THE 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()); 
     } 
    } 
}