Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regular Expression Match All 5 Digit Numbers but None Larger

Tags:

python

regex

I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, 53232, 21032, 40021 etc... I can handle the simpler case of any string of 5 digits with [0-9]{5}, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular expression to match only 5 digit numbers?

like image 799
Bryce Thomas Avatar asked Aug 20 '10 16:08

Bryce Thomas


People also ask

How do you match digits in Python?

Python Regex Metacharacters[0-9] matches any single decimal digit character—any character between '0' and '9' , inclusive. The full expression [0-9][0-9][0-9] matches any sequence of three decimal digit characters. In this case, s matches because it contains three consecutive decimal digit characters, '123' .

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.


1 Answers

>>> import re >>> s="four digits 1234 five digits 56789 six digits 012345" >>> re.findall(r"\D(\d{5})\D", s) ['56789'] 

if they can occur at the very beginning or the very end, it's easier to pad the string than mess with special cases

>>> re.findall(r"\D(\d{5})\D", " "+s+" ") 
like image 149
John La Rooy Avatar answered Oct 05 '22 00:10

John La Rooy