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"
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?
You need to anchor your expression. Add a
$or\Zat 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 withmatch().