Using escapes In regular expressions with a backslash - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

\( represents a left parenthesis, and \) represents a right parenthesis.

Without the backslashes, Java treats the parenthesis as a grouping element.

To escape a backslash, code two slashes in a row.

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{4}");
    Matcher matcher = pattern.matcher("(779) 148-1212");
    if (matcher.matches())
      System.out.println("Match.");
    else//from   ww w  . j  a va  2 s . co m
      System.out.println("Does not match.");
  }

}

Related Tutorials