Reputation: 63
I want to find phone number inside text using regex. My forula for phone number is:
(?:(?:\+?\d*\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{3})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
The numer is being found when it is in one line without any other text. But when it is in the middle of some text it is not being found. How can I fix that?
Here is the link with the example: regexr.com/3rf0l
Upvotes: 0
Views: 36
Reputation: 422
That's because your regex ends by $
, which is an anchor for the end of the line/document (depending on your multiline settings).
For example, in the string 1a2b
, the regex [a-z]$
will match b
but not a
, because it's not at the end of the string, while [a-z]
will match both.
Remove it and it will work:
(?:(?:\+?\d*\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{3})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?
Upvotes: 2