Match if string starts with n digits and no more

Viewed 180

I have strings like 6202_52_55_1959.txt

I want to match those which starts with 3 digits and no more.

So 6202_52_55_1959.txt should not match but 620_52_55_1959.txt should.

import re
regexp = re.compile(r'^\d{3}')
file = r'6202_52_55_1959.txt'
print(regexp.search(file))

<re.Match object; span=(0, 3), match='620'> #I dont want this example to match

How can I get it to only match if there are three digits and no more following?

2 Answers

Use the pattern ^\d{3}(?=\D):

inp = ["6202_52_55_1959.txt", "620_52_55_1959.txt"]
for i in inp:
    if re.search(r'^\d{3}(?=\D)', i):
        print("MATCH:    " + i)
    else:
        print("NO MATCH: " + i)

This prints:

NO MATCH: 6202_52_55_1959.txt
MATCH:    620_52_55_1959.txt

The regex pattern used here says to match:

^       from the start of the string
\d{3}   3 digits
(?=\D)  then assert that what follows is NOT a digit (includes end of string)
Related