gpt4 book ai didi

python - 我的正则表达式旨在查找美国的电话号码,但没有寻找正确的模式

转载 作者:行者123 更新时间:2023-12-01 02:23:05 25 4
gpt4 key购买 nike

我正在使用 python 3.6,正在学习“自动化无聊的东西”类(class),并尝试学习如何在正则表达式中使用 VERBOSE 模式。当执行下面的代码时,不知何故打印结果是:

[('123-', ''), ('415-', ''), ('905-', '')]

有人可以告诉我我做错了什么吗?我希望代码返回字符串中的两个电话号码。

import re

phoneNum = re.compile(r'''
(\d\d\d-)| # area code without parentheses but with dash
(\(\d\d\d\) ) # -or- area code with parentheses and no dash
\d\d\d # first 3 digits
- # second dash
\d\d\d\d # last 4 digits''', re.VERBOSE)

print(phoneNum.findall('(415) 123-2342 and 415-905-1234 are the numbers.'))

最佳答案

第一个分组错误,需要交替\d\d\d-\(\d\d\d\)并且还要转义空格在括号数字之后,否则它将被视为格式化空白(因为您使用的是 re.VERBOSE)。

正则表达式可以修复为

(?:\d{3}-|   # area code without parentheses but with dash
\(\d{3}\)\ ) # -or- area code with parentheses and no dash
\d{3} # first 3 digits
- # second dash
\d{4} # last 4 digits

注意第二行的\。请参阅regex demo 。您可以在表达式的开头/结尾添加 \b 以将数字作为整个单词进行匹配。

使用

import re
phoneNum = re.compile(r'''
(?:\d{3}-| # area code without parentheses but with dash
\(\d{3}\)\ ) # -or- area code with parentheses and no dash
\d{3} # first 3 digits
- # second dash
\d{4} # last 4 digits''', re.VERBOSE)
print(phoneNum.findall('(415) 123-2342 and 415-905-1234 are the numbers.'))
# => ['(415) 123-2342', '415-905-1234']

请参阅Python demo .

关于python - 我的正则表达式旨在查找美国的电话号码,但没有寻找正确的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743000/

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