Regex expression for E.164 not working

user2638180 :

I'm using the following code:

    Pattern p = Pattern.compile("^\\+?[1-9]\\d{1,14}$"); 
    stringNumber=stringNumber.replace(" ","");
    Matcher m = p.matcher(stringNumber);


    if (!m.matches()) 
    {
    [...]
    }

And pattern, which is supposed to properly detect numbers in E.164 format, isn't working as I think it should, as it's giving valid as a E.164 phone number, a number in the format XXXXXXXXX, being X all digit between 0 and 9. And as much as I look to the pattern I can't understand why.

The less restrictive pattern "^\+?\d{10,14}$" is indeed working as it detects that a number of XXXXXXXXX doesn't fit in the format.

Maybe the last pattern is enough for my application purposes, but I'd like to use the first one (one that could determine that a phone number is in E.164 format in every case) just to get a wider range of possibilities even if those possibilities are rare.

What might be causing that unexpected behavior with the first pattern?

tima :

To make the number have + at the front, your regex should be ^\\+[1-9]\\d{1,14}$. Notice the removal of ? which meant that + was optional.

Also, the reason the second pattern did not match the input was not because of the + but because the second pattern requires a 10 digit number at least, and the example you had was with 9 digits.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471591&siteId=1