python regex doesn't match '+' in phone number

Viewed 71

I have regex to match Australian phone numbers


import re

phoneRegex = re.compile(r"\b((\+61|0061|0)?\s?)?\d{3}\s?\d{3}\s?\d{3}\b")

lists = phoneRegex.finditer(
    " +61745856965, 0061456123789, 0478563214, 0412 452 789, 61 789963258")

for list in lists:
    print(list.group())

Output is

0061456123789
0478563214
0412 452 789
 789963258

What do I need to match first number +61745856965 ?

Thanks

1 Answers

The initial \b is causing the problem, because + is not a word character, so \b\+ is never going to match +61 except when preceded by a word char (which it won't be).

Use this:

phoneRegex = re.compile(r"((\+61|\b0061|\b0)?\s?)?\d{3}\s?\d{3}\s?\d{3}\b")

The change here is to apply the \b only to the non "+61" prefix.


If you want to match the last example 61 789963258 including the leading 61, add "\b61 " to the list of prefixes:

phoneRegex = re.compile(r"((\+61|\b0061|\b61 |\b0)?\s?)?\d{3}\s?\d{3}\s?\d{3}\b")
Related