Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my Regex is not detecting phone numbers written in certain patterns?

I have a regex to check phone numbers in a text. Please check below.

(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}

This regex works fine but it does not work well if I write it this way.

  1. Ex 1: 088 11 22 458
  2. Ex 2: +1 88 11 22 458

How can I modify the regex to fix this bug?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add an optional + at the start, allow two or three digits in the area code and add an alternative to match two double digits and then a chunk of three digits in the end:

(?:\+?\d[\s-]?)?[([\s-]{0,2}\d{2,3}[)\]\s-]{0,2}(?:\d{3}[\s-]?\d{4}|\d{2}[\s-]?\d{2}[\s-]?\d{3})

See the regex demo. Details:

  • (?:\+?\d[\s-]?)? – an optional occurrence of an optional +, a digit and then a whitespace or a hyphen
  • [([\s-]{0,2} – zero, one or two (, [, whitespace or hyphen chars
  • \d{2,3}two or three digits
  • [)\]\s-]{0,2} – zero, one or two ), ], whitespace or hyphen chars
  • (?:\d{3}[\s-]?\d{4}|\d{2}[\s-]?\d{2}[\s-]?\d{3}) – either of
    • \d{3}[\s-]?\d{4} – three digits, an optional whitespace or -, four digits
    • | – or
    • \d{2}[\s-]?\d{2}[\s-]?\d{3} – two digits, an optional whitespace or -, two digits, an optional whitespace or -, three digits

You might also think of adding numeric boundaries to disallow matches that have other digits on the left (with the negative (?<!\d) lookbehind) and right (with the negative (?!\d) lookahead):

(?:\+?(?<!\d)\d[\s-]?)?[([\s-]{0,2}(?<!\d)\d{2,3}[)\]\s-]{0,2}(?:\d{3}[\s-]?\d{4}|\d{2}[\s-]?\d{2}[\s-]?\d{3})(?!\d)

See this regex demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading