请引用python3正则表达式HOWTO
https://docs.python.org/3/howto/regex.html#performing-matches
>>> p = re.compile('\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']
我已经读到对于包含 '\'
的正则表达式,原始字符串应该像 r'\d+'
一样使用,但是在这个代码片段中 re .compile('\d+')
在不使用 r
说明符的情况下使用。它工作正常。为什么它首先起作用?为什么这个正则表达式前面不需要“r”?
最佳答案
它恰好可以工作,因为 '\d'
不对应于特殊字符,如 '\n'
或 '\t'
做。有时原始字符串与常规字符串版本相同。不过,通常情况下,原始字符串将确保您的表达式不会出现任何意外。
关于python - 为什么表达包含 '\' 的正则表达式在没有原始字符串的情况下也能工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915134/