Hanalei Hanalei - 4 months ago 11
Java Question

Use regex to validate a phone number?

if((phone.length() > 10 &&
((phone.contains("+1" + "((\\\\d{3}-)){1,2}\\\\d{4}"))
|| (phone.contains("+966" + "d{9}"))))
|| ((phone.length() == 10) &&
!(phone.contains("(") && !(phone.contains(")") &&
!(phone.contains("-")))))) //phone doesnt contain special characters if its a saudi no.
{
....
}
else {
....
}


Hello all :) I'm trying to create a code that validates the following formats of phone numbers and NOTHING else:


  1. +9665xxxxxxxx

  2. 05xxxxxxxx

  3. +1(xxx)xxx-xxxx

  4. +1xxxxxxxxxx

  5. xxx-xxx-xxxx



I've tried to do this in the code above, where the phone number is represented as String "phone". However I think I've done it incorrectly, especially the regex. Can anyone tell me if there is a simpler way to do this? Or a simplified version of the code? Would it be easier if I used a series of if() statements instead? I'm sorry I'm very new to java so I'm sure I've done something wrong.

Answer

Something like this should do the trick:

Pattern pattern = Pattern.compile(
    "\\+9665\\d{8}|05\\d{8}|\\+1\\(\\d{3}\\)\\d{3}-\\d{4}|\\+1\\d{10}|\\d{3}-\\d{3}-\\d{4}"
);
Matcher matcher = pattern.matcher("+966512345678");
System.out.println(matcher.matches());

Output:

true
Comments