Looking for alternative to javascript lookbehind for phone number regex pattern

Viewed 52

I have a regex pattern to check for input phone number. Regex pattern is:

(@"((?:\(?[2-9](?(?=1)1[02-9]|(?(?=0)0[1-9]|\d{2}))\)?\D{0,3})(?:\(?[2-9](?(?=1)1[02-9]|\d{2})\)?\D{0,3})\d{4})"

This works fine for Server side validation and fails for client-side. I get the Invalid group error.

I am fairly new to regex and by digging around I found out that it is because JS doesn't support lookbehind.

I tried to apply the - inversing the string technique but the pattern is too complicated. Could someone please help. Thanks in advance.

1 Answers

All your conditional constructs need to be replaced with a non-capturing group that contains a negative lookahead at the start. In general, it looks like

(?(?=0)01|\d{2}) = (?:(?=0)01|(?!0)\d{2})

That is, you convert a conditional group into a non-capturing group, and add restrictions to each alternative in the group. (?:(?=0)01|(?!0)\d{2}) matches 01 if the next char is 0, else, if the next char is not 0, match any two digits (but not if they start with 0 of course).

So, in your concrete case, change

  • (?(?=1)1[02-9]|(?(?=0)0[1-9]|\d{2})) -> (?:(?=1)1[02-9]|(?:(?=0)0[1-9]|(?!0)\d{2}))
  • (?(?=1)1[02-9]|\d{2}) -> (?:(?=1)1[02-9]|(?!1)\d{2})

The exact JavaScript equivalent for the PCRE pattern is

((?:\(?[2-9](?:(?=1)1[02-9]|(?:(?=0)0[1-9]|(?!0)\d{2}))\)?\D{0,3})(?:\(?[2-9](?:(?=1)1[02-9]|(?!1)\d{2})\)?\D{0,3})\d{4})

See the regex demo.

However, some of the groupings are redundant, so you may shorten it to

\(?[2-9](?:(?=1)1[02-9]|(?:(?=0)0[1-9]|(?!0)\d{2}))\)?\D{0,3}\(?[2-9](?:(?=1)1[02-9]|(?!1)\d{2})\)?\D{0,3}\d{4}
Related