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?
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' .
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.
>>> 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+" ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With