您好,我有一串文本,其中包含多种不同格式的电话号码,我需要能够仅提取电话号码。
例如:“嗨,我的名字是 marc,我的电话号码是 03-123456,我想要 2 瓶 0.5L 的水”
可能的电话格式:
- 所有电话号码均以区号 03 或 70 或 71 或 76 开头(无其他选项)
- 所有电话号码均是区号后的 6 位数字
- 不同的消息具有不同的格式,例如 03-123456 或 03123456 或 03 123 456 或 03 123456 或 03/123456(您懂的)
我可以使用python中的find函数通过查找(03或70或76或71)来找到索引,但我无法找到最后一个数字的索引。
number_start = message.find('03' or '70' or '76' or '71')
有什么想法吗?
最佳答案
你可以使用
\b(?:03|7[016])[- /]?\d{3} ?\d{3}\b
说明
\b
单词边界(?:03|7[016])
匹配03
之一70
71
76
[-/]?
可选地匹配-
空格或/
\d{3} ?\d{3}
匹配 6 位数字,第 3 位数字后可选空格\b
单词边界
例如
import re
regex = r"\b(?:03|7[016])[- /]?\d{3} ?\d{3}\b"
test_str = "Hi my name is marc and my phone number is 03-123456 and i would like 2 bottles of water 0.5L"
matches = re.search(regex, test_str)
if matches:
print(matches.group())
输出
03-123456
关于python - 使用不同格式的正则表达式提取电话号码python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64076427/