python - 如何在Python中使用正则表达式?

标签 python regex python-2.7 python-2.x

我一定错过了一些简单的东西 - 无论我做什么,我都无法让我的正则表达式匹配任何字符串:

[~] $ python2.7
Python 2.7.12 (default, Aug 13 2016, 19:37:25) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> s = "   405489796130    "
>>> regex = "\b[0-9]{15}|[0-9]{12}\b"
>>> for str in re.findall(regex, s):
...     print(str)
... 
>>> for str in re.finditer(regex, s):
...     print(str)
... 
>>> print("Hi")
Hi
>>> 

正则表达式 "\b[0-9]{15}|[0-9]{12}\b"应该明确匹配提供的字符串(该字符串包含 12 位数字的子字符串...)。

我什至将此文本和正则表达式放入 https://regexr.com/该网站的正则表达式找到了子字符串 - 为什么 Python 不能?

最佳答案

你必须转义反斜杠。

regex = "\\b[0-9]{15}|[0-9]{12}\\b"

关于python - 如何在Python中使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964726/

相关文章:

python - 在 Azure Functions 中安装requirements.txt 时无法解析对 numpy 的依赖关系

python - 如何配置 syslog 以在 Python 中进行日志记录

regex - 去正则表达式不匹配

hgignore 文件中的正则表达式负向后视

python - 将数字应用于字符串的序列生成

python - 将相同的应用程序/代码部署到 Elastic Beanstalk 服务器和工作环境的正确方法是什么?

python - ssh 与 winpexpect

python在路径中使用通配符执行shell命令

python - 使用 fileinput 写入文件会产生问题

python - 将十六进制摘要字符串转换回原始字符串