1

I'm trying to make a regex which can match a phone number and so tell me if the phone number is either valid or not.

I would like to verify if there is a country id before the phone number, this one is well formated.

For example : +(33)0123456789 I want to be sure if the user start to type the first parenthesis it must be followed by number and ended by a closing parenthesis.

I have succeeded with PCRE engine

^[+]?((\()?(?(2)[0-9]{1,4})(?(2)\)))?([0-9]{2}){1}([\.\- ]?[0-9]{2}){4}$

But I realized this way doesn't work with javascript engine, conditional is not supported.

^[+]?((\()?((?=\2)[0-9]{1,4})((?=\2)\)))?([0-9]{2}){1}([\.\- ]?[0-9]{2}){4}$

It doesn't fill my needs. I want to check if the first parenthesis is set then it must be followed by number and a closing parenthesis.

So I ask you if there is a workaround in javascript to do this ?

Some help would be really appreciated, thank you :)

2
  • It sounds as if you just want to make (\d{1,4}) optional. Try ^\+?((?:\([0-9]{1,4})\))?([0-9]{2})([. -]?[0-9]{2}){4}$, see this demo. Commented Dec 12, 2018 at 13:49
  • Exactly what I want to do ! It seems that conditional regex is not what I need for this case. I stubbornly tried to use it but your workaround is much more simplen thank you Commented Dec 12, 2018 at 13:53

1 Answer 1

1

The ((\()?(?(2)[0-9]{1,4})(?(2)\)))? part of the regex is matching an optional sequence of smaller patterns. (\()? matches an optional ( and places it in Group 2. Then, (?(2)[0-9]{1,4}) matches 1 to 4 digits if Group 2 matched. Then (?(2)\)) matches ) if Group 2 matched. Basically, this is equal to (?:\([0-9]{1,4})\))?.

Thus, you need no conditional construct here.

You may use

^\+?(?:\([0-9]{1,4})\)?[0-9]{2}(?:[. -]?[0-9]{2}){4}$

See the regex demo

Details

  • ^ - start of string
  • \+? - an optional +
  • (?:\([0-9]{1,4})\)? - an optional sequence: (, 1 to 4 digits and )
  • [0-9]{2} - 2 digits
  • (?:[. -]?[0-9]{2}){4} - 4 occurrences of an optional space, dot or - followed with 2 digits
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.