2016-12-26 31 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(@"\_+"), "_"); 
関連する問題