2010-09-13 72 views

回答

3

,需要一個「計數」參數超載的數量應該做你想做的事情。

Regex cat = new Regex("cat"); 
string input = "cat cat cat cat cat"; 
Console.WriteLine(cat.Replace(input, "dog", 3)); 
Console.ReadLine(); 

輸出應該是: 「狗狗狗貓貓」

+0

感謝您的示例!完美的作品! – 2010-09-13 21:41:23

0

下面的代碼可能會有所幫助。

string s = "lionlionlionlionlionlionlionlionlionlion"; 
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("lion"); 
s = r.Replace(s, "donkey", 6, 0); 
Console.Out.Write(s); 

輸出是donkeydonkeydonkeydonkeydonkeydonkeylionlionlionlion

您還可以動態地更改替換字符串如下:

private string replaceMe(System.Text.RegularExpressions.Match m) 
{ 
    return "donkey[" + m.Index.ToString() + "]"; 
} 

private replaceStr() { 
    string s = "lionlionlionlionlionlionlionlionlionlion"; 
    Regex r = new Regex("lion"); 
    s = r.Replace(s, new System.Text.RegularExpressions.MatchEvaluator(replaceMe),6); 
    Console.Out.Write(s); 
} 

則輸出donkey[0]donkey[4]donkey[8]donkey[12]donkey[16]donkey[20]lionlionlionlion