2016-07-05 183 views
0

我試圖取代用下面的代碼字符串的一部分字符串的確切部分:C#替換包含特殊字符

public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) 
{ 

     string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find; 
     return Regex.Replace(input, textToFind, replace); 

} 

但是,當我有字符串中的特殊字符,這並不工作。我試圖逃避的人物,但沒有運氣...

下面是一個例子,我有以下字符串:

Peter[='111222'] + APeter[='111222'] 

我想@更換Peter[='111222']所以結果應該是: @ + APeter[='111222']。使用給定的代碼,字符串保持不變,沒有任何變化。

請注意,我可能會有許多不同的情況與其他特殊字符,如Steven.intr[A:B;>1], Sssdf.len, asd.ind等,所以在我的情況下,我需要找到不同格式的精確匹配。

在此先感謝!

+0

你可以張貼一些例子 – Rohit

+0

肯定:喬治[= 1],QC.ind,asd.len。它應該與不包含特殊字符的字符串一起使用。以下是我需要替換的另一個字符串示例:「asd.len + hasd.len」 - >替換「asd.len」 - >結果:「@ + hasd.len」。 – Venco

回答

0

不匹配單詞邊界,匹配空格和/或開始/結束字符串。這將適用於非字母數字。

此外,您需要轉義您的字符串,並從replace中刪除單詞邊界(在我的情況下,空格和/或開頭/行尾):您可以使用lookahead/lookbehind做到這一點。

所以這一切說:

public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) 
{ 
    string textToFind = matchWholeWord ? string.Format(@"(?<=^|\s){0}(?=$|\s)", Regex.Escape(find)) : Regex.Escape(find); 
    return Regex.Replace(input, textToFind, replace); 
} 

I've made a demonstrating fiddle

+0

嗨,請看看你的代碼不工作的例子:[小提琴的例子](https://dotnetfiddle.net/1UAB3Q) – Venco

+0

我在發佈之前搞砸了,並從正則表達式中刪除了「字符串的起點」...正確的'textToFind'應該是'(?<=^| \ s){0}(?= [$ | \ s])''。我正在編輯和更改小提琴 – Jcl

+0

你走了,對不起,這只是一個小錯字(解釋是正確的)。您可能希望在「{0}' – Jcl