首页 > 解决方案 > 从字符串中提取澳大利亚电话号码

问题描述

我正在尝试匹配澳大利亚的电话号码。因为数字可以以 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']

你能指出我正确的方向吗?

标签: pythonregex

解决方案


>>> pattern = r'((?:0|\+61|61)[234578]\d{8})'
>>> find_ph = re.findall(pattern, txt)
>>> print(find_ph)
['0412345677', '+61412345677', '61412345677']

您遇到的问题是,仅前缀部分的括号告诉 findall 函数仅捕获这些字符,同时匹配所有其余字符。(顺便说一句,它findall不是find_all,你的字符串在变量txtnot中text)。

相反,使用 (?:0|+61|61) 将其设为非捕获组。现在您捕获与整个模式匹配的整个字符串。


推荐阅读