更换带有双反斜线单反斜线 [英] Replace single backslash with double backslash

查看:270
本文介绍了更换带有双反斜线单反斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来很简单,不是吗?好吧,我不知道。

It seems simple enough, right? Well, I don't know.

下面是我想要的代码:

input = Regex.Replace(input, "\\", "\\\\\\");



不过,我收到一个错误,

However, I'm receiving an error,

ArgumentException的是未处理 - 解析\ - 非法\的模式结束

ArgumentException was unhandled - parsing "\" - Illegal \ at end of pattern.

我该怎么做呢?

推荐答案

第一个应该是\\\ \,而不是\\。它的工作原理是这样的:

The first one should be "\\\\", not "\\". It works like this:


  • 您已经写了\\

  • 这相当于在一个字符串序列 \

  • 的正则表达式引擎然后读取此,意为反斜杠这不是逃避什么,所以它抛出一个错误。

  • You have written "\\".
  • This translates to the sequence \ in a string.
  • The regex engine then reads this, which translates as backslash which isn't escaping anything, so it throws an error.

使用正则表达式,它要容易得多使用逐字字符串。在这种情况下,逐字的字符串将是 @\\。当使用逐字的字符串,你只需要考虑转义正则表达式引擎,反斜杠字面上对待。第二个字符串也将是 @\\,因为它不会被正则表达式引擎来解释。

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.

这篇关于更换带有双反斜线单反斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆