Python 我的正则表达式设计用于查找基于美国的电话号码,但没有找到正确的模式

Python 我的正则表达式设计用于查找基于美国的电话号码,但没有找到正确的模式,python,regex,Python,Regex,我正在使用Python3.6,学习“自动化无聊的东西”课程,并试图学习如何在正则表达式中使用详细模式。执行以下代码时,打印结果为: [('123-','',('415-','',('905-','')] 有人能告诉我我做错了什么吗?我希望代码在字符串中返回两个电话号码 import re phoneNum = re.compile(r''' (\d\d\d-)| # area code without parentheses but with dash (\(\d\d\d\) ) # -or

我正在使用Python3.6,学习“自动化无聊的东西”课程,并试图学习如何在正则表达式中使用详细模式。执行以下代码时,打印结果为:

[('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\)
,并转义括号数字后的空格,否则它将被视为格式化空白(因为您使用的是
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
注意第二行的
\
。看。您可以在表达式的开头/结尾添加
\b
,以将数字作为一个单词进行匹配

使用


请参阅。

谢谢您的回复。我对编码还不熟悉,所以我仍然不确定一些运算符和语法。你能给我解释一下吗?:在代码的第一行是什么?每次我使用管道字符时都必须使用它吗?@Steve抱歉,我忘了提到您还必须使用非捕获组(语法是
(?:…)
),这样
re.findall
就不会只返回捕获的子字符串。如果您使用
re.finditer
并抓取
match.group(0)
您不必关心您使用的是哪种组。
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']