繁体   English   中英

正则表达式替换中无法识别的转义序列

[英]Unrecognized escape sequence in Regex Replace

我有以下几点:

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 \\_.

如何更改代码,以便可以与任何字符一起使用?

以下代码按预期工作:

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

删除反斜杠,很好!

如果您不是替换模式的熟练者:

使用.net提供的方法转义“转义符”

这可以通过使用System.Text.RegularExpressions.Regex.Escape来实现

例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM