蟒蛇查找电话号码



我尝试了以下代码:

import re
r = re.compile(r'''(+)*d*                 # optional + sign for international calls
([" "-)]{,1}d+)*    # main chain of numbers, numbers separated by a space, ) or a hyphen
''',re.VERBOSE)
print(r.findall('+00 0000 0000 is my number and +44-787-77950 was my uk number'))

预期结果

[('+00',' 0000',' 0000'),('+44','-787','-77950')]

或者,更好:

['+00 0000 0000','+44-787-77950']

但生活并没有那么容易,相反,我得到了一个神秘的

[('+', ' 0000'), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('+', '44'), ('', ''), ('', '787'), ('', ''), ('', '77950'), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', ''), ('', '')]

为什么它表现得很奇怪,我将如何解决它?

编辑 - 我的例子不是最好的,我希望"+somenumber"是可选的 - 并非所有发送给我的电话号码都是国际电话号码,因此不必包含 + 符号

很抱歉没有说清楚。

到目前为止,最接近我想要的东西似乎是

import re
r = re.compile(r'''(+)?(d+)                 # optional + sign for international calls
([" "-)]{,1}d+)+    # main chain of numbers, numbers separated by a space, ) or a hyphen
''',re.VERBOSE)
print(r.findall('+00 0000 0000 is my number and +44-787-77950 was my uk number'))

这给了

[('+', '00', ' 0000'), ('+', '4', '4'), ('', '78', '7'), ('', '7795', '0')]

快速修复您的模式是

+?d+(?:[- )]+d+)+

请参阅正则表达式演示。请注意,使用非捕获组有助于避免在re.findall调用的结果中创建元组列表。

  • +?- 可选(1 或 0(加号
  • d+- 1+ 位数字
  • (?:- 非捕获组的开始:
    • [- )]+- 1 个或多个-spaces,个字符
    • d+- 1+ 位数字
  • )+- 1 次或多次重复(以这种方式量化整个(?:...)模式序列,符号和数字至少需要一次并作为一个序列(。

蟒蛇演示:

import re
rx = r"+?d+(?:[- )]+d+)+"
s = "+00 0000 0000 is my number and +44-787-77950 was my uk number"
print(re.findall(rx, s))
# => ['+00 0000 0000', '+44-787-77950']

所有令牌都是可选的,因此正则表达式可以并且将匹配空字符串。

我想你会想要使用以下:

(+)?(d+)([ -)]?d+)

您可以使用此正则表达式来捕获电话号码,它将跳过空格或破折号并仅保留数字本身:

s = '+00 0000 0000 is my number and +44-787-77950 was my uk number'   
p = '(+d+)(?:[s-])(d+)(?:[s-])(d+)'
re.findall(p, s)
[('+00', '0000', '0000'), ('+44', '787', '77950')]

该模式意味着:

  • (+d+)- 查找 + 后跟一个或多个数字
  • (?:[s-])- 后跟空格或短划线,在非捕获组中(表示它 需要在那里,但不返回匹配的对象(
  • (d+)- 另一个或多个数字

然后,您可以轻松地用空格/破折号构建电话号码join.

for number in re.findall(p, s):
print '-'.join(number)
+00-0000-0000
+44-787-77950

最新更新