georgexu
>>> mm = "c:\\a\\b\\c"
>>> mm
\'c:\\a\\b\\c\'
>>> print(mm)
c:\a\b\c
>>> re.match("c:\\\\",mm).group()
\'c:\\\'
>>> ret = re.match("c:\\\\",mm).group()
>>> print(ret)
c:\
>>> ret = re.match("c:\\\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\a",mm).group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: \'NoneType\' object has no attribute \'group\'
>>>

说明

Python中字符串前面加上 r 表示原生字符串

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

Python里的原生字符串很好地解决了这个问题,有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a

分类:

技术点:

相关文章:

  • 2021-10-28
  • 2022-01-09
  • 2022-02-06
  • 2021-12-22
  • 2021-12-29
  • 2022-01-28
  • 2021-12-26
  • 2022-12-23
猜你喜欢
  • 2021-09-16
  • 2021-09-24
  • 2021-12-11
  • 2022-01-30
  • 2022-02-01
  • 2022-02-18
  • 2021-05-19
相关资源
相似解决方案