用双反斜杠替换单反斜杠 [英] Replace single backslash with double backslash

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

问题描述

看起来很简单吧?好吧,我不知道.

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 未处理 - 解析" - 模式末尾的非法 .

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

我该怎么做?

推荐答案

第一个应该是 "\\",而不是 "\".它是这样工作的:

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

  • 您已经编写了"\".
  • 这会转换为字符串中的序列 .
  • 然后正则表达式引擎读取此内容,将其转换为不转义任何内容的反斜杠,因此会引发错误.

使用正则表达式,使用逐字字符串"要容易得多.在这种情况下,逐字字符串将是 @"\".使用逐字字符串时,您只需要考虑为正则表达式引擎转义,因为反斜杠是按字面处理的.第二个字符串也将是 @"\",因为它不会被正则表达式引擎解释.

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天全站免登陆