Home > Back-end >  Why my Regex is not detecting phone numbers written in certain patterns?
Why my Regex is not detecting phone numbers written in certain patterns?

Time:04-26

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?

CodePudding user response:

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.

CodePudding user response:

I would use this regex: [\ \(\[]?\d[\(\[\s-]?\d[\s-]?\d[\)\]\s-]?\d[\s-]?\d[\s-]?\d[\s-]?\d[\s-]?\d[\s-]?\d[\s-]?\d

It allows to use delimiters in any place. Sometimes phone numbers are delimiter so that it will be easier to remember them.

For example:

  • 088 111-2-111
  • (088)11-22-33-4
  • Related