【问题标题】:Python phonenumber regex doesn't work good enoughPython phonenumber 正则表达式不够好
【发布时间】:2012-03-31 11:38:14
【问题描述】:

我在我的代码中使用了这个正则表达式代码:

pattern = re.compile('\d{3,4}(\/?)(\d{6,6})')
m= pattern.match('0481/987421')
if m:
    print "yes"
else:
    print "no"

这是一个适用于以下电话号码的正则表达式:dddd/dddddddd 所以前 3 位或 4 位数字,然后是斜线与否,然后正好是 6 位数字。 它工作正常,例如 21/484135 不起作用,其他错误的事情也不起作用。 但是这个正则表达式的问题是,当我的第一个字符是正确的并且我在它后面随机输入任何内容时,它仍然会打印“是”。我的意思是这样的:0481/9874214879516874 我认为因为正则表达式匹配它返回的前 11 个字符,所以它匹配并且它后面的内容并不重要。

我该如何解决这个问题?

【问题讨论】:

  • 我知道这似乎离题了,但是...这些是什么电话号码
  • 啊...\d{3, 4} 真的把我搞砸了。与此同时,有人发布了$主播。你现在应该去投票了。

标签: python regex match


【解决方案1】:

我建议使用phonenumbers 模块而不是编写自己的正则表达式。以下是解析比利时电话号码的示例:

>>> x = phonenumbers.parse("0481/987421", "BE")
>>> x
PhoneNumber(country_code=32,
            national_number=481987421L,
            extension=None,
            italian_leading_zero=False,
            country_code_source=None,
            preferred_domestic_carrier_code=None)

它会在无效的电话号码上抛出异常:

>>> x = phonenumbers.parse("0481/9874214879516874", "BE")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/phonenumbers/phonenumberutil.py", line 2038, in parse
    "The string supplied is too long to be a phone number.")
phonenumbers.phonenumberutil.NumberParseException: (4) The string supplied is too long to be a phone number.

【讨论】:

    【解决方案2】:

    你需要锚定你的表达。在其末尾添加$\Z 以确保没有任何后续内容。您还可以添加 ^ 以将其锚定在字符串的开头,尽管与 match() 一起使用时不需要这样做。

    pattern = re.compile(r"^\d{3,4}/?\d{6}\Z")
    

    【讨论】:

    • 哦不,当我现在删除斜线时它不再匹配了:/
    • 你使用的是同一个版本的 Python 吗?
    • Python 使用大写 \Z(而其他使用小写 \z),已更正。请参阅ideone 的工作示例。
    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多