我一定错过了一些简单的东西 - 无论我做什么,我都无法让我的正则表达式匹配任何字符串:
[~] $ 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/