2012-06-15 26 views
6

我一直在努力解決一個問題,任何幫助,將不勝感激。C#正則表達式 - 匹配和替換,自動遞增

問題:我有一段,我想替換出現多次的變量(Variable = @Variable)。這是很容易的部分,但我遇到困難的部分是試圖用不同的值替換變量。

我需要爲每個事件具有不同的值。例如,我有一個函數爲每個變量進行計算。我有這樣遠遠低於是:

private string SetVariables(string input, string pattern){ 

    Regex rx = new Regex(pattern); 
    MatchCollection matches = rx.Matches(input); 
    int i = 1; 
    if(matches.Count > 0) 
    { 
     foreach(Match match in matches) 
     { 
      rx.Replace(match.ToString(), getReplacementNumber(i)); 
      i++ 
     } 
    } 

我能夠相互替換,我需要從getReplacementNumber返回的數字變量(i)函數,但我怎麼把它放回我的原始輸入以匹配集合中找到的相同順序替換值?

在此先感謝!

馬庫斯

+0

什麼是'getReplacementNumber(我)'的返回類型? –

回答

8

使用Replace採用一個MatchEvaluator作爲它的第二個參數的過載。

string result = rx.Replace(input, match => { return getReplacementNumber(i++); }); 

我假設這裏getReplacementNumber(int i)返回string。如果不是,則必須將結果轉換爲字符串。

看到它聯機工作:ideone

+0

工作就像一個魅力!感謝您的幫助。我非常感謝! –