gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:44 25 4
gpt4 key购买 nike

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

[~] $ 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com