python - 正则表达式为什么"\"(反斜杠)需要4个"\"(反斜杠)来转义?
巴扎黑
巴扎黑 2017-04-18 09:54:15
0
3
1000

对于反斜杠"\"为什么不能直接使用"\\"来转义,而是要使用4个反斜杠,这是网上搜出来的一个解释,没有看明白,求解释一下?

与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠.


Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个"\\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

巴扎黑
巴扎黑

reply all(3)
小葫芦

In fact, it has been described very clearly. First of all, this regular statement is a string, and to express one backslash in a Python string requires two backslashes, so in fact, when the regular parser is given here, there is only one backslash. Slash, and in regular expressions, two backslashes are needed to express one backslash, so a total of four are needed.

黄舟

The first two and the last two are used to escape into backslashes in programming languages,

Convert to two backslashes and then escape to one backslash in the regular expression.

伊谢尔伦
`r"\"` 会造成语法错的。这样做的目的是,r 字符串通常用于正则,而末尾出现单数个 `\` 的正则是有问题的,所以 Python 的 r 字符串不允许以单数个 `\` 结尾。

Okay, damn markdown... It seems that only writing like this will make it normal...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!