python - 从字符串中提取澳大利亚电话号码
问题描述
我正在尝试匹配澳大利亚的电话号码。因为数字可以以 0 或 +61 或 61 开头,然后是 2 或 3 或 4 或 5 或 7 或 8,然后是 8 位数字。
txt = "My phone number is 0412345677 or +61412345677 or 61412345677"
find_ph = re.find_all(r'(0|\+61|61)[234578]\d{8}', text)
find_ph
返回
['0', '61']
但我希望它回来
['0412345677', '+61412345677' or '61412345677']
你能指出我正确的方向吗?
解决方案
>>> pattern = r'((?:0|\+61|61)[234578]\d{8})'
>>> find_ph = re.findall(pattern, txt)
>>> print(find_ph)
['0412345677', '+61412345677', '61412345677']
您遇到的问题是,仅前缀部分的括号告诉 findall 函数仅捕获这些字符,同时匹配所有其余字符。(顺便说一句,它findall
不是find_all
,你的字符串在变量txt
not中text
)。
相反,使用 (?:0|+61|61) 将其设为非捕获组。现在您捕获与整个模式匹配的整个字符串。
推荐阅读
- rx-java2 - 重复自身直到找到期望值的 RxObservable
- java - “builder.replace”是什么类型的复杂性?
- enterprise-architect - 在 Gitbook 中使用 Enterprise Architect API 获取文档
- python - 如何在 Django 中删除不可为空的字段?
- javascript - 将 HyperApp Web 应用程序上传到 github,我要上传哪些文件?
- c++ - constexpr(即常量初始化)模板变量的初始化顺序是否有保证?
- firefox - Imacro 脚本在 Firefox 中不起作用
- tsql - 根据分组值创建序列号
- python - 如何使用 open() 打开特定路径?
- python - 让 LED 在莫尔斯中闪烁点或破折号