gpt4 book ai didi

python - python "backrefrence conditions"和 "regex"模块中的 "re"无法按预期工作

转载 作者:行者123 更新时间:2023-12-04 10:56:54 24 4
gpt4 key购买 nike

我正在尝试仅匹配字符串中存在的北美数字; (123)456-7890 和 123-456-7890 都是北美电话号码可接受的表示格式,这意味着任何其他模式都不应匹配。

注意: python3.7和pycharm Editor正在使用。

以下是用字符串表示的电话号码:

123-456-7890
(123)456-7890
(123)-456-7890
(123-456-7890
1234567890
123 456 7890

我尝试使用 (\()?\d{3}(?(1)\)|-)\d{3}-\d{4} 正则表达式,它确实使用反向引用条件来匹配所需的电话号码, 下面的 python 代码包括:

import regex
st = """
123-456-7890
(123)456-7890
(123)-456-7890
(123-456-7890
1234567890
123 456 7890
"""
pat = regex.compile(r'(\()?\d{3}(?(1)\)|-)\d{3}-\d{4}', regex.I)
out = pat.findall(st)
print(out)

Output using findall method: ['', '(', '']

Output using search(st).group() method which returns just the first match: 123-456-7890

Matches should be : 123-456-7890
(123)456-7890



我的问题是:为什么 findall 方法应该像在 regex 101 website 中那样完美地返回匹配的模式,现在却返回像 ['', '(', ''] 这样令人讨厌的结果?

我已经尝试过 regex 101 website 中的正则表达式,它工作得很好,但在这里没有。

注意: 我正在使用 sams 自学正则表达式书,在第 134 页建议了这个问题的最佳解决方案,上面是它的 python 实现。

最佳答案

您的正则表达式是正确的,但如果您使用 findall 则它会自动打印所有捕获的组。最好使用 finditer 并打印 .group().group(0) :

>>> pat = regex.compile(r'^(\()?\d{3}(?(1)\)|-)\d{3}-\d{4}$', regex.M)
>>> for m in pat.finditer(st):
... print (m.group())
...
123-456-7890
(123)456-7890

关于python - python "backrefrence conditions"和 "regex"模块中的 "re"无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116156/

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