Home > Mobile >  Re-write regex expression number filtering Python
Re-write regex expression number filtering Python

Time:01-18

Given a string like 'hello 0796XXXXXX. TODAY IS UR LUCKY DAY£500 Cash', I use the following regex

re.findall(r"(\b07\d*|\b08\d*|\b09\d*)", t) to receive the numbers that start with 07 | 08 | 09 and are followed by 0 or more digits. ['0796'] is the result.

How do I have to re-write the code so that \b and \d* are not repeated? I tried re.findall(r"\b(07|08|09)\d*)", t) e.g., but unfortunately it does not work and only returns [07].

Thanks

CodePudding user response:

Avoid the parentheses, and put the 0 aside that is also repeated:

re.findall(r"\b0[789]\d*", t)

CodePudding user response:

regex = r"(07|08|09)\d*"
re.findall(regex, text)
  •  Tags:  
  • Related