Reference group in regular expression - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

\1 refers to the first capture group.

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("\\w(\\d)-\\w\\1");
    Matcher matcher = pattern.matcher("r2-d2");
    if (matcher.matches())
      System.out.println("Match.");
    else/*from w w  w  .  j  a v a2  s .  com*/
      System.out.println("Does not match.");
  }

}

Related Tutorials