M.Hamel
M.Hamel

Reputation: 415

Why is my regex is not matching a phone number that I require?

My book "Automate the boring stuff with Python" has this complex regex which tries to get the 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 the phone number that I think should match with the regex but it doesn't. I was using regex101 and here is the link to my regex : https://regex101.com/r/OIMqNB/1. Could someone please tell me where am I going wrong?

Upvotes: 3

Views: 209

Answers (2)

SyncroIT
SyncroIT

Reputation: 1568

I've fixed it for you, you have just messed in placing a ?. Here's the new regex: https://regex101.com/r/OIMqNB/2

Upvotes: 1

Defrag
Defrag

Reputation: 416

that regex is correct, you just added a newline that broke the regex in two slices:

((\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'll see it works as intended.

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

It's a common error while using visual helpers, just double check your regex is on the same line everytime you see some odd behaviours

Upvotes: 3

Related Questions