2012-03-18 200 views
0

我想在下面的字符串<b>c++</b>更換c++正則表達式嵌套量詞+

string cssOld = Regex.Replace(
    "Select the projects entry and then select VC++ directories. Select show", 
    "c++", "<b>${0}</b>", RegexOptions.IgnoreCase); 

"Select the projects entry and then select VC++ directories. Select show" 

我希望它使用

"Select the projects entry and then select V<b>C++</b> directories. Select show" 

林這段代碼是

我收到以下錯誤:
System.ArgumentException: parsing "c++" - Nested quantifier +.

此代碼可以很好地與其他文本(!C++)配合使用。它看起來像+運算符導致正則表達式庫引發異常。

回答

2

你應該regex特殊字符轉義:

string cssOld = Regex.Replace(
    "Select the projects entry and then select VC++ directories. Select show ", 
    @"c\+\+", "${0}", RegexOptions.IgnoreCase); 
+0

好的,非常感謝。我只需要爲+運營商提供服務,或者是否還有其他可能導致此異常的運營商(*,&,\ etc)? – 2012-03-18 17:00:11

+0

您可以檢查此其他特殊字符:http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions。其中包括以下內容:(\,*,+,?,|,{,[,(,),^,$,。,#和空白) – ionden 2012-03-18 17:05:17

+0

謝謝。 Regex.Escape也做了這項工作。所以我把我的代碼改爲: string cssOld = Regex.Replace(Regex.Escape(「Select the projects entry and then select VC++ directories。Select show 」),Regex.Escape(「C++」),「$ { 0}「,RegexOptions.IgnoreCase); 它工作正常。謝謝你們。 – 2012-03-18 17:14:35

4

+是正則表達式中的一個特殊字符;它意味着「匹配一個或多個前面的字符」。

要匹配文字+字符,你需要通過編寫\+

(一個@""字面內)要匹配任意的文本字符,使用Regex.Escape逃脫它。

+0

好感謝了很多。我只需要爲+運營商提供服務,或者是否還有其他可能導致此異常的運營商(*,&,\ etc)? – 2012-03-18 17:02:37

+0

噢,謝謝。 Regex.Escape也做了這項工作。所以我把我的代碼改爲: string cssOld = Regex.Replace(Regex.Escape(「Select the projects entry and then select VC++ directories。Select show 」),Regex.Escape(「C++」),「$ { 0}「,RegexOptions.IgnoreCase); 它工作正常。謝謝你們。 – 2012-03-18 17:14:44