Create regular expression for U.S. phone numbers with an optional area code - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Create regular expression for U.S. phone numbers with an optional area code

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}\\)\\s?)?\\d{3}-\\d{4}");
    Matcher matcher = pattern.matcher("555-1234");
    if (matcher.matches())
      System.out.println("Match.");
    else//from w  w w . j  a v a2  s  . c  o m
      System.out.println("Does not match.");
  }

}

Related Tutorials