2011-09-21 35 views
2

所以我有一些字符串,我想更換支架的一些事件中。使用正則表達式查找封裝在[]項目,然後替換它們

現在,這是我到目前爲止已經完成。和它的作品

string answerText = "This is an [example] string"; 
Match match = Regex.Match(answerText, @"\[(.*?)\]"); 

if(match.Success) 
{ 
    if(match.Value.Equals("[example]")) 
    { 
     answerText = answerText.Replace(match.Value, "awsome"); 
    } 
} 

我試圖找出是如何做到這一點,如果答案文字看起來像這樣

string answerText = "This is an [example1] [example2] [example3] string"; 
+1

更普遍的是,你可能想看看平衡的正則表達式,例如http://stackoverflow.com/questions/4284827/regular-expression-that-uses-balancing-groups –

+1

當然,你不只是尋找[Regex.Replace](http://msdn.microsoft.com/en -us/library/xwewhkd1.aspx)方法? *在指定的輸入字符串內,用指定的替換字符串替換所有匹配正則表達式模式的字符串。* –

+1

是否會有嵌套? – NullUserException

回答

0

利用我在原來的職位建議通過串幾次循環,直到我沒有匹配的解決方案解決了這個。

3

是否有任何理由你爲什麼不這樣做而不是使用正則表達式?

string answerText = "This is an [example] string"; 
answerText.Replace("[example]", "awsome"); 
+1

也許他不知道括號內的文字是什麼? – 2011-09-21 14:37:09

+1

@CodeMonkey,這也是我的想法。使用的正則表達式支持該假設。 –

+0

因此是問號。這個問題似乎表明他將根據實際值測試比賽,看看他是否需要替換它們,在這種情況下,您不需要使用正則表達式... –

0

您可以使用Regex的Replace方法,如下所示。

 Regex.Replace(inputString, "\\[" + matchValue + "\\]", "ReplaceText", RegexOptions.IgnoreCase); 

希望這有助於!

1

這個怎麼樣

string answerText = "This is an [example1] [example2] [example3] string"; 
string pattern = @"\[(.*?)\]"; 
answerText = Regex.Replace(answerText, pattern, "awesome"); 
+0

提示:問號使模式「懶惰」,即使用可用的最短匹配。將這與帶回調函數的Replace-Overload結合起來,你就可以在你的模式上「切換大小寫」... – eFloh

+0

這不會用「awesome」代替所有[whatever]嗎? –

+0

@Trikks是的,這就是這是做什麼。 – stema

相關問題