对于反斜杠"\"为什么不能直接使用"\\"来转义,而是要使用4个反斜杠,这是网上搜出来的一个解释,没有看明白,求解释一下?
与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠.
Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个"\\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。
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.
Okay, damn markdown... It seems that only writing like this will make it normal...