[英]Python phone number regex
我需要您的帮助:我需要在一段文字中找到所有电话号码,因此我需要匹配不同的电话号码格式,例如:+420 123 123 123、123 123 123,+ 420123123123和/或123123123。
如果我在搜索方法中使用正则表达式模式,则效果很好,但如果我使用findall方法,则仅返回空白列表。
import re
def detect_numbers(text):
phone_regex = re.compile(r"(\+420)?(\s*)?\d{3}(\s*)?\d{3}(\s*)?\d{3}")
print(phone_regex.findall(text))
https://docs.python.org/3/library/re.html#re.findall
Findall返回元组列表,每个元组代表一个匹配项中的组。 您正在对空格进行分组,但未对实际数字进行分组。
尝试将数字也分组的正则表达式:
r"(\+420)?(\s*)?(\d{3})(\s*)?\(d{3})(\s*)?\(d{3})"
例如
def detect_numbers(text):
phone_regex = re.compile(r"(\+420)?\s*?(\d{3})\s*?(\d{3})\s*?(\d{3})")
print(phone_regex.findall(text))
detect_numbers("so I need to match +420 123 123 123, also 123 123 123, also +420123123123 and also 123123123. Can y")
打印:
[('+420', '123', '123', '123'), ('', '123', '123', '123'), ('+420', '123', '123', '123'), ('', '123', '123', '123')]
然后,您可以将组匹配字符串连接起来以获取数字,例如
def detect_numbers(text):
phone_regex = re.compile(r"(\+420)?\s*?(\d{3})\s*?(\d{3})\s*?(\d{3})")
groups = phone_regex.findall(text)
for g in groups:
print("".join(g))
detect_numbers("so I need to match +420 123 123 123, also 123 123 123, also +420123123123 and also 123123123. Can y")
打印:
+420123123123
123123123
+420123123123
123123123
尝试如下所示的正则表达式,因为手机号码包含数字
"/[^0-9 +\-]/"
如果您要以某个特定号码开头的用户,如下所示
preg_match('\+420\d{9}/', mobilenumber)
假设您的文字表现相对良好。 然后,一个简单的模式可能是恢复所有至少9个数字,空格的序列,并且-
可选地在re.findall
加一个+
。
除非您的文本包含一些奇怪的工件或算术运算,否则应该可以解决问题。 此外,格式上的松动将允许查找包含格式错误的数字。
import re
def find_phone_numbers(text):
phones = re.findall('(?:\+ *)?\d[\d\- ]{7,}\d', text)
return [phone.replace('-', '').replace(' ', '') for phone in phones]
例:
text = "My phone numbers are 123123123, +234-123-3231 and + 555 123 1234"
print(find_phone_numbers(text)) # ['123123123', '+2341233231', '+5551231234']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.