Python phonenumber正则表达式不';我做得不够好

Python phonenumber正则表达式不';我做得不够好,python,regex,match,Python,Regex,Match,我在代码中使用了以下正则表达式代码: 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不工作,其他错误的东西也不工作。 但这个正则表达

我在代码中使用了以下正则表达式代码:

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个字符,所以它返回匹配的结果,后面的内容并不重要


如何解决此问题?

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

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

>>> 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.
>>x=phonenumbers.parse(“0481/9874214879516874”,“BE”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/local/lib/python2.7/dist packages/phonenumbers/phonenumberrutil.py”,第2038行,在parse中
“提供的字符串太长,不能作为电话号码。”)
phonenumbers.phonenumberutil.NumberParseException:(4)提供的字符串太长,不能作为电话号码。

我知道这似乎有点离题,但是……这些电话号码是什么?啊……这个
\d{3,4}
真的把我搞糊涂了。与此同时,有人发布了
$
锚。你现在可能应该去投票了。哦,不,当我现在删除斜杠时,斜杠不再匹配了:/你使用的是同一版本的Python吗?Python使用大写字母
\Z
(而其他人使用小写字母
\Z
),更正了。请参阅上的工作示例。
>>> 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.