Java Regular Expressions to Validate phone numbers

Ducky :

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"); 
                }
             }
      }
  }
Patrick Parker :

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

Guess you like

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