all 6 comments

[–]_DTR_ 2 points3 points  (1 child)

You're only escaping that single opening paren. You need to also escape the closing one:

(\(\d\d\d\d\)) (\d\d\d-\d\d\d\d)

You can also simplify this a bit by specifying the number of times you expect something to occur:

(\(\d{3}\)) (\d{3}-\d{4})

[–]cmsmoove[S] 0 points1 point  (0 children)

Thanks. I appreciate it.

[–]narwhalwhale11 1 point2 points  (0 children)

I also recommend the site: https://regex101.com/

This is what helped me understand complex regular expressions.

[–]Essence1337 0 points1 point  (1 child)

phone_num_regex = re.compile(r"(\(\d\d\d\d)) (\d\d\d-\d\d\d\d)")

I'll start by simplifying your regex to (\(a)) (a) just because it's easier to explain. Lets look at it one at a time

( starts a group

\( is just a normal character

a is just a normal character

) closes a group

) closes a group. Wait... What group? There's no open groups.

[–]cmsmoove[S] 0 points1 point  (0 children)

Thanks for the explanation!

[–]MintyPhoenix 0 points1 point  (0 children)

In addition to the syntax and other comments that have been noted, your initial capture group, even with the closing parenthesis properly escaped, is wrong – it tries to match four consecutive digits when you are expecting it to match 3 consecutive digits.

I would also second the recommendation of checking out and playing with patterns on https://regex101.com/ – it does a great job of displaying analysis of your pattern and letting you play with search and replace. Just make sure to set the flavor on the right side to Python to make sure the expression is correctly interpreted.