2012-10-25 59 views
2

我已經看到了一個如何在C#中實現正則表達式全局替換的例子,其中涉及到組,但我已經空了。所以我寫了我自己的。任何人都可以提出一個更好的方法來做到這一點正則表達式全局替換組

static void Main(string[] args) 
{ 
    Regex re = new Regex(@"word(\d)-(\d)"); 
    string input = "start word1-2 filler word3-4 end"; 
    StringBuilder output = new StringBuilder(); 
    int beg = 0; 
    Match match = re.Match(input); 
    while (match.Success) 
    { 
     // get string before match 
     output.Append(input.Substring(beg, match.Index - beg)); 

     // replace "wordX-Y" with "wdX-Y" 
     string repl = "wd" + match.Groups[1].Value + "-" + match.Groups[2].Value; 
     // get replacement string 
     output.Append(re.Replace(input.Substring(match.Index, match.Length), repl)); 

     // get string after match 
     Match nmatch = match.NextMatch(); 
     int end = (nmatch.Success) ? nmatch.Index : input.Length; 
     output.Append(input.Substring(match.Index + match.Length, end - (match.Index + match.Length))); 

     beg = end; 
     match = nmatch; 
    } 
    if (beg == 0) 
     output.Append(input); 
} 
+2

請解釋_exactly_你想達到的目標。特別是投入和想要的產出。 – Oded

+0

基本上,我只是試圖編寫一個算法,可以應用於給定的字符串,並全局替換所有出現的匹配(使用它的組值)(即貫穿整個字符串)。這太糟糕了,沒有可以傳遞給Replace的「全局」枚舉來實現這一點。 –

回答

2

您可以通過Replace一個MatchEvaluator。這是一個代表,需要Match並返回要替換的字符串。

例如

string output = re.Replace(
    input, 
    m => "wd" + m.Groups[1].Value + "-" + m.Groups[2].Value); 

或者,和我對此不太確定,你可以使用前瞻 - 「檢查該文如下,但不包括其在比賽中。」語法是(?=whatver)所以我認爲你需要類似word(?=\d-\d)然後用wd替換它。

+0

你的第一個解決方案正是我所希望的!一行代替我的整個'while'循環。謝謝! –

+0

我覺得你對這件事太過分了。問題中沒有任何內容或隨附的示例代碼表明MatchEvaluator是必需的。實際上,他試圖解決的問題並不存在:[替換方法](http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx)**爲**全局。 –

+0

@Alan我錯過了簡單使用'$'替換Guffa所顯示的內容,但是這裏需要_some_形式的反向引用(或向前看)。 – Rawling

4

你不需要做任何邏輯可言,那更換可以在替換字符串中使用組引用來完成:

string output = Regex.Replace(input, @"word(\d)-(\d)", "wd$1-$2");