Python电话号码正则表达式无法正常工作 [英] Python phonenumber regex doesn't work good enough

查看:81
本文介绍了Python电话号码正则表达式无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this regex code I use in my code:

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个字符,所以它返回匹配的内容,而后面的内容无关紧要.

It's a regex that should work for phonenumbers like this: dddd/dddddddd so first 3 or 4 digits, then a slash or not and then exactly 6 digits. It works fine, for example 21/484135 doesn't work and other wrong things also don't work. But the problem of this regex is, when my first characters are right and I type anything random behind it it would still print "yes". I mean something like this: 0481/9874214879516874 I think because the regex matches for the first 11 characters it returns it matches and it doesn't matter what comes behind it.

我该如何解决这个问题?

How can I solve this problem?

推荐答案

您需要锚定表达式.在其末尾添加$\Z以确保没有后续内容.您还可以添加^来将其锚定在字符串的开头,但是与match()一起使用时不需要.

You need to anchor your expression. Add a $ or \Z at the end of it to make sure nothing follows. You could also add ^ to anchor it at the beginning of string, altho that is not required when used with match().

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

这篇关于Python电话号码正则表达式无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆