2016-12-26 54 views
0

我有以下幾點:無法識別的轉義序列替換

String source = "this-is--a-string----"; 

我需要刪除連續破折號所以我用:

String output = Regex.Replace(source, @"\-+", "-"); 

有時我需要刪除其他重複的角色,所以我嘗試:

String source = "this_is__a_string____"; 
String output = Regex.Replace(source, @"\_+", "_"); 

在這種情況下,我得到了錯誤:

Unhandled Exception: System.AggregateException: 
One or more errors occurred. (parsing '\_+' - Unrecognized escape sequence \\_.) 
---> System.ArgumentException: parsing '\_+' - Unrecognized escape sequence \\_. 

如何更改我的代碼,以便我可以將它與任何字符一起使用?

回答

1

下面的代碼工作正常:

string source = "this_is__a_string____"; 
string output = Regex.Replace(source, @"_+", "_"); 
+0

我看你從刪除\查詢字符串...所以沒有必要在正則表達式中,對吧? –

+0

有沒有必要逃避_,它在正則表達式中沒有特殊的含義,它是字面上的下劃線。 – Damian

0

刪除反斜槓,好走!

0

如果不掌握在替換模式:

Escape the "Escapes" with a method provided by .net

這可以通過使用來實現 System.Text.RegularExpressions.Regex.Escape

例子:

String source = "this_is__a_string____"; 
String output = Regex.Replace(source, Regex.Escape(@"\_+"), "_");