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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With