- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试仅匹配字符串中存在的北美数字; (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
则它会自动打印所有捕获的组。最好使用 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/
我正在尝试仅匹配字符串中存在的北美数字; (123)456-7890 和 123-456-7890 都是北美电话号码可接受的表示格式,这意味着任何其他模式都不应匹配。 注意: python3.7和py
我是一名优秀的程序员,十分优秀!