[英]Escape single and double back slashes
I am trying to replace a string using regex, however I can't seem to find a way to escape the single backslashes for the regex with the double backslashes of the string. 我正在尝试使用正则表达式替换字符串,但是我似乎找不到任何方法来用字符串的双反斜杠转义正则表达式的单个反斜杠。
My string literal (this is being read from a text file, as is) 我的字符串文字(按原样从文本文件中读取)
-s \"t\"
and I want to replace it with (again, as a string literal) 我想用(再次作为字符串文字)替换它
-s \"n\"
The best I have been able to come up with is 我能想到的最好的是
schedule = Regex.Replace(schedule, "-s\s\\\"\w\\\"", "-s \\\"n\\\"");
The middle argument doesn't compile though, because of the single and double backslashes. 由于单反斜杠和双反斜杠,中间参数没有编译。 It will accept one or the other, but not both (regardless of weather I use @).
它将接受一个或另一个,但不能同时接受(不管我使用@的天气如何)。
I don't use regexes that much so it may be a simple one but I'm pretty stuck! 我不使用正则表达式,所以它可能很简单,但是我很卡住!
Thanks 谢谢
The problem is happening because \\
have a special meaning both for strings and regular expressions so it normally needs to be double escaped unless you use @
and added to the problem here is the presence of "
itself inside the string which needs to be escaped. 之所以会出现问题,是因为
\\
对字符串和正则表达式都有特殊的含义,因此除非您使用@
并将其添加到问题中,否则通常需要对其进行两次转义,这是因为在字符串中存在"
本身"
,需要对其进行转义。
Try the following: 请尝试以下操作:
schedule = Regex.Replace(schedule, @"-s\s\\""\w\\""", @"-s \""n\""");
After using @
, \\
doesn't have a special meaning inside strings, but it still have a special meaning inside regular expression expression so it needs to be escaped only once if it is needed literally. 在使用
@
, \\
在字符串内部没有特殊含义,但是在正则表达式表达式内部仍具有特殊含义,因此,如果确实需要它,则只需对其进行一次转义。
Also now you need to use ""
to escape "
inside the string (how would you escape it otherwise, since \\
doesn't have a special meaning anymore) . 同样,现在您还需要在字符串内部使用
""
转义"
(否则将如何转义,因为\\
不再具有特殊含义) 。
This works: 这有效:
var schedule = @"-s \""t\""";
// value is -s \"t\"
schedule = Regex.Replace(schedule, @"-s\s\\""\w\\""", @"-s \""n\""");
// value is -s \"n\"
The escaping is complicated because \\
and "
have special meanings both in how you encode strings in C# and in regex. The search pattern is (without any escaping) the C# string -s\\s\\\\"\\w\\\\"
, which tells regex to look for a literal \\
and a literal "
. 转义很复杂,因为
\\
和"
在C#和regex中对字符串编码的方式都有特殊含义。搜索模式是(没有任何转义)C#字符串-s\\s\\\\"\\w\\\\"
,它告诉正则表达式寻找文字\\
和文字"
。 The replacement string is -s \\"n\\"
, because you don't need to escape the backslashes in a replacement string. 替换字符串是
-s \\"n\\"
,因为您不需要在替换字符串中转义反斜杠。
You could, of course, write this with normal strings ( "..."
) instead of verbatim strings ( @"..."
), but it'd get way messier. 你可以,当然,写这与正常的字符串(
"..."
),而不是逐字字符串( @"..."
),但它会得到这样混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.