Hanalei Hanalei - 2 months ago 6
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.


Something like this should do the trick:

Pattern pattern = Pattern.compile(
Matcher matcher = pattern.matcher("+966512345678");