Why is my regex not matching the required phone number?

My book Automating Drilling with Python has this complex regex that tries to get a phone number in a given string:

((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s(ext|x|ext.)\s*\d{2,5})?)

222-666-7777 ext 322 is a phone number which I think should match the regex, but it isn't. I used regex101 and here is a link to my regex: https://regex101.com/r/OIMqNB/1 . Can someone please tell me where am I going wrong?

+3


source to share


2 answers


that the regex is correct, you just added a newline that split the regex into two segments:

((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}
(\s*(ext|x|ext.)\s*\d{2,5})?)

      

just hit canc after {4} and put it on the same line in your regex101 link and you will see that it works as intended.



((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s*(ext|x|ext.)\s*\d{2,5})?)

      

This is a common mistake when using visual helpers, just double check that your regex is on the same line every time you see odd behavior

+3


source


I fixed it for you, you just messed up the placement ?

. Here's a new regex: https://regex101.com/r/OIMqNB/2



+1


source







All Articles