Let a user enter the area code for a phone number with or without parentheses. - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Let a user enter the area code for a phone number with or without parentheses.

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("((\\d{3} )|(\\(\\d{3}\\) ))?\\d{3}-\\d{4}");
    Matcher matcher = pattern.matcher("559 555-1234");
    if (matcher.matches())
      System.out.println("Match.");
    else/*www . j  a  v a 2s .c om*/
      System.out.println("Does not match.");
  }

}

Related Tutorials