Regex for phone number allowing 9 or 10 digits


I am trying to validate a regex which

  • allows 10 digits
  • if digit starts with 672 then it should only allow total 9 digits

I have tried below regex

It works for 10 digits but if number starts with 672 then also it allows 10 digits.
Could anyone help how can I fix this?

>Solution :

First of all, the capturing group in your regex is redundant, it would make sense to wrap the part of the pattern between ^ and $ to only use single occurrences of the anchors.

To fix the issue, you need to make sure the first three digits matched by \d{10} are not 672, and you can achieve that with a negative lookahead:


See the regex demo. Details:

  • ^ – start of string
  • (?: – start of a group:
    • (?!672)\d{10} – no 672 substring check is triggered and then ten digits are matched
  • | – or
    • 672\d{6}672 and six digits
  • ) – end of the group
  • $ – end of string.

Leave a ReplyCancel reply