Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex for int with at least 4 digits

I am just learning regex and I'm a bit confused here. I've got a string from which I want to extract an int with at least 4 digits and at most 7 digits. I tried it as follows:

>>> import re
>>> teststring = 'abcd123efg123456'
>>> re.match(r"[0-9]{4,7}$", teststring)

Where I was expecting 123456, unfortunately this results in nothing at all. Could anybody help me out a little bit here?

like image 777
kramer65 Avatar asked May 02 '13 22:05

kramer65


1 Answers

You can also use:

re.findall(r"[0-9]{4,7}", teststring)

Which will return a list of all substrings that match your regex, in your case ['123456']

If you're interested in just the first matched substring, then you can write this as:

next(iter(re.findall(r"[0-9]{4,7}", teststring)), None)
like image 56
galarant Avatar answered Oct 26 '22 23:10

galarant