简体   繁体   English

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

[英]Extract phone number using regex with different formats python

Hi I have a string of texts which include a phone number in many different formats, I need to be able to extract just the phone number.嗨,我有一串文本,其中包含许多不同格式的电话号码,我需要能够仅提取电话号码。

Eg: "Hi my name is marc and my phone number is 03-123456 and i would like 2 bottles of water 0.5L"例如:“嗨,我的名字是 marc,我的电话号码是 03-123456,我想要 2 瓶 0.5L 的水”

possible phone formats:可能的电话格式:

  • All phone numbers begin with area code either 03 or 70 or 71 or 76 (no other option)所有电话号码都以区号 03 或 70 或 71 或 76 开头(没有其他选项)
  • all phone numbers are 6 digits after the area code所有电话号码都是区号后的 6 位数字
  • Different msgs have different formats such as 03-123456 or 03123456 or 03 123 456 or 03 123456 or 03/123456 (you get the idea)不同的消息有不同的格式,例如 03-123456 或 03123456 或 03 123 456 或 03 123456 或 03/123456(你懂的)

I am able to find the index using find function in python by looking for (03 or 70 or 76 or 71) but I am not able to find the index of the last number.我可以通过查找(03 或 70 或 76 或 71)在 python 中使用 find 函数找到索引,但我无法找到最后一个数字的索引。

number_start = message.find('03' or '70' or '76' or '71')

Any ideas?有任何想法吗?

You could use你可以用

\b(?:03|7[016])[- /]?\d{3} ?\d{3}\b

Explanation解释

  • \\b A word boundary \\b一个词边界
  • (?:03|7[016]) Match one of 03 70 71 76 (?:03|7[016])匹配03 70 71 76
  • [- /]? Optionally match - a space or /可选匹配-空格或/
  • \\d{3} ?\\d{3} Match 6 digits with an optional space after the 3rd digits \\d{3} ?\\d{3}匹配 6 位数字,第 3 位数字后有一个可选的空格
  • \\b A word boundary \\b一个词边界

Regex demo |正则表达式演示| Python demo Python 演示

For example例如

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())

Output输出

03-123456

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM