python - 使用不同格式的正则表达式提取电话号码python

标签 python regex

您好,我有一串文本,其中包含多种不同格式的电话号码,我需要能够仅提取电话号码。

例如:“嗨,我的名字是 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 单词边界

Regex demo | Python demo

例如

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/

相关文章:

python - "Flatten"列表中的一串单词

python - 不明白这个 ModuleNotFoundError 的原因

python - 如何在 Flask 中使用 SQLAlchemy 调用数据库函数?

javascript - 正则表达式美化缩小的 CSS

regex - 在 Linux 中使用正则表达式重命名文件

python - 同步访问时,在共享内存中使用 numpy 数组会很慢

php - 如何使用 WHERE 条件从表中的字符串中查找特定值?

c# - 包含数字的单词的正则表达式掩码

StackOverflow 风格的 Javascript 正则表达式图像标签?

Python "Value Error: cannot delete array elements"——为什么我会得到这个?