Search code examples
javascriptregexpcre

Conditional regex javascript


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 :)


Solution

  • 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.