2015-06-28 201 views
0

內字符序列的所有實例假設我有以下內容的文本文件:如何替換字符串

longtextwith some space and unicode escape like this \u003ca

我想要替換的\u003c所有實例/ OCCURENCES /序列無視事實上,a是尾隨的。就像「尋找一系列字符的所有實例,忽略情況並替換它」。

我想這已經沒有任何反應:

using (var sr = new StreamReader("1.txt")) 
{ 
    string result = sr.ReadToEnd(); 

    result = Regex.Replace(result, @"\b\\u003c\b", "<", RegexOptions.IgnoreCase); 
} 

這個變體還會產生不是我想要的結果:

result = Regex.Replace(result, @"\\u003c", "<", RegexOptions.IgnoreCase); 
result = Regex.Replace(result, "\u003c", "<", RegexOptions.IgnoreCase); 
result = Regex.Replace(result, "\b\\u003c\b", "<", RegexOptions.IgnoreCase); 

在Lua這一工作:str = string.gsub(str, '\\u003e', '>')

在這種情況下,我對.NET編碼和解碼unicode,ascii等提供的選項不感興趣。

+1

使用正則表達式編輯工具,讓您調試正則表達式。問題必須在模式中。例如在使用@時你有雙倍\\。看到這個答案如果你不想購買RegExBuddy http://stackoverflow.com/questions/132405/free-alternative-to-regxbuddy – n00b

回答

1

你的模式應該是@「\ b \ u003c」。既然你用@定義了它,你不需要在u003c前面加一個雙反斜線。另外,\ b意味着一個單詞的邊界,所以你當前的模式不會匹配一個尾隨的a,因爲它不在單詞的邊界上。

如需進一步參考,請查看RegEx.Escape方法,以幫助確保您的模式正確轉義。如果您經常使用正則表達式,請幫助自己並查閱www.RegExBuddy.com。我幾年前購買它並喜歡它。這是一款出色的工具,而且價格低廉。

2

爲什麼不使用String.Replace

string str = inputString.Replace("\\u003c", "<"); 

如果你想不區分大小寫的替代,試試這個:

var regex = new Regex(@" \\u003c", RegexOptions.IgnoreCase); 
string str = regex.Replace(inputString, "<");