Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular Expressions to Validate phone numbers

Tags:

java

regex

In the following code I am trying to get the output to be the different formatting of phone numbers and if it is either valid or not. I figured everything out but the Java Regular Expression code on line 11 the string pattern.

 import java.util.regex.*;

  public class MatchPhoneNumbers {
   public static void main(String[] args) {           
     String[] testStrings = {               
               /* Following are valid phone number examples */             
              "(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
              /* Following are invalid phone numbers */ 
              "(1234567890)","123)4567890", "12345678901", "(1)234567890",
              "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};

             // TODO: Modify the following line. Use your regular expression here
              String pattern = "^/d(?:-/d{3}){3}/d$";    
             // current pattern recognizes any string of digits           
             // Apply regular expression to each test string           
             for(String inputString : testStrings) {
                System.out.print(inputString + ": "); 
                if (inputString.matches(pattern)) {     
                    System.out.println("Valid"); 
                } else {     
                    System.out.println("Invalid"); 
                }
             }
      }
  }
like image 688
Ducky Avatar asked Feb 08 '17 04:02

Ducky


2 Answers

Basically, you need to take 3 or 4 different patterns and combine them with "|":

String pattern = "\\d{10}|(?:\\d{3}-){2}\\d{4}|\\(\\d{3}\\)\\d{3}-?\\d{4}";
  • \d{10} matches 1234567890
  • (?:\d{3}-){2}\d{4} matches 123-456-7890
  • \(\d{3}\)\d{3}-?\d{4} matches (123)456-7890 or (123)4567890
like image 186
Patrick Parker Avatar answered Sep 21 '22 07:09

Patrick Parker


international phone number regex

String str=  "^\\s?((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?\\s?";


 if (Pattern.compile(str).matcher(" +33 - 123 456 789 ").matches()) {
        System.out.println("yes");
    } else {
        System.out.println("no");
    } 
like image 37
Anurag Gupta Avatar answered Sep 25 '22 07:09

Anurag Gupta