将单反斜杠替换为双反斜杠
看起来很简单,对吧?嗯,我不知道。
这是我正在尝试的代码:
input = Regex.Replace(input, "\\", "\\\\\\");
但是,我收到错误,
ArgumentException 未处理 - 解析“\” - 模式末尾的 \ 非法。
我该怎么做?
It seems simple enough, right? Well, I don't know.
Here's the code I'm trying:
input = Regex.Replace(input, "\\", "\\\\\\");
However, I'm receiving an error,
ArgumentException was unhandled - parsing "\" - Illegal \ at end of pattern.
How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
第一个应该是
"\\\\"
,而不是"\\"
。它的工作原理如下:"\\"
。\
。通过正则表达式,使用“逐字字符串”要容易得多。在这种情况下,逐字字符串将为
@"\\"
。使用逐字字符串时,您只需考虑对正则表达式引擎进行转义,因为反斜杠是按字面处理的。第二个字符串也将是@"\\"
,因为正则表达式引擎不会解释它。The first one should be
"\\\\"
, not"\\"
. It works like this:"\\"
.\
in a string.With regex, it's much easier to use a "verbatim string". In this case the verbatim string would be
@"\\"
. When using verbatim strings you only have to consider escaping for the regex engine, as backslashes are treated literally. The second string will also be@"\\"
, as it will not be interpreted by the regex engine.如果您想用两个反斜杠替换一个反斜杠,通过使用
@"..."
作为字符串文字的格式(也称为逐字字符串。这样就更容易看出这是从
\
到\\
的替换。If you want to replace one backslash with two, it might be clearer to eliminate one level of escaping in the regular expression by using
@"..."
as the format for your string literals, also known as a verbatim string. It is then easier to see thatis a replacement from
\
to\\
.我知道现在来帮助你已经太晚了,也许其他人会从中受益。无论如何,这对我有用:
而且我发现它更简单。
干杯!
I know it's too late to help you, maybe someone else will benefit from this. Anyway this worked for me:
and I find it even more simplier.
Cheers!
第一个参数是字符串 \\,即正则表达式中的 \。
第二个参数不经过正则表达式处理,因此在替换时会按原样放置。
The first parameter is string \\ which is \ in regex.
The second parameter is not processed by regex, so it will put it as is, when replacing.
如果您打算稍后在正则表达式模式中使用输入,那么使用 Regex.Encode 可能是个好主意。
If you intend to use the input in a regex pattern later, it can be a good idea to use Regex.Encode.
我已经尝试过所有这些例子,但没有成功。
我有一个“//”,但我不想改变它。我只需要更改“/”
这个正则表达式帮助了我:
string myString =“https://example.com/example/example/example”;
字符串结果 = Regex.Replace(myString, @"(?
我得到了 - “https://example.com//example//example//example”
I have tried all these examples, but without success.
I had a "//" and I didn't want to change it. I only needed to change the "/"
This regex helped me:
string myString = "https://example.com/example/example/example";
string result = Regex.Replace(myString, @"(?<!/)/(?!/)", "//");
and I got - "https://example.com//example//example//example"