python - 为什么表达包含 '\' 的正则表达式在没有原始字符串的情况下也能工作。

标签 python regex python-3.4

请引用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/

相关文章:

正则表达式查找匹配文件扩展名的文件,除非文件名包含字符串

python - 安全配置解析器 : sections and environment variables

python - Anaconda & Tensorflow & Skflow : dnn() got an unexpected keyword argument 'keep_prob'

c# - 正则表达式排除括号

python - 从命令提示符运行单元测试

Java正则表达式替换开头的每个数字

apache-spark - JavaPackage 对象不可调用错误 : Pyspark

python - 为什么一组数字看起来是有序的?

Python:变量范围和 profile.run

python - 如何评估高度不平衡数据的准确性(使用朴素贝叶斯模型)?