2012-07-18 35 views
2

如果我做這樣的事情:更換多個字符串替換()與單Regex.Replace()

someString.Replace("abc","").Replace("def","").Replace(@"c:\Windows","") 

我怎麼能替換成

Regex.Replace(someString," \\here I don't know what the pattern should be") 

我試着這樣的:

Regex.Replace(someString, @"(?:abc|def|c:\Windows)") 

,但它沒有工作

UPD ...

問題是,當我通過這樣的

Regex.Replace(someString, @"(?:abc|def|"+aPath+")") 
+0

確保所有的反斜線轉義。 '\'應該是'\\' – justderb 2012-07-18 20:12:40

回答

6
`But it didnt work` doesn't say much helpfull! 

路徑試試這個:

someString = Regex.Replace(someString, @"(?:abc|def|ghi|c:\\Windows)", "") 

它沒有工作時,我嘗試過。我認爲你的代碼不工作的原因是你忘記了替換字符串,你必須在路徑中轉義反斜槓。

3

我假設「沒有工作」的東西是你的C:\ Windows替代品。你需要

someString = Regex.Replace(someString, @"(?:abc|def|C:\\windows)",""); 

問題是你需要逃避你的反斜槓。正則表達式中一個未轉義的反斜槓有意義。特別是在這種情況下,\ W實際上匹配任何非字母數字字符。

編輯逃跑的任意字符串,可以使用Regex.Escape(yourString);

+0

如果我通過這樣的路徑: Regex.Replace(someString,@「(?: abc | def |」+ aPath +「,」「) – Agzam 2012-07-18 20:27:43

+0

使用Regex.Escape 。 往上看。 – aquinas 2012-07-19 03:35:32