作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我是一名优秀的程序员,十分优秀!