Using the Captured Text of a Group within a Pattern - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Using the Captured Text of a Group within a Pattern

Demo Code

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

public class Main {
  public static void main(String[] args) throws Exception {
    // Compile regular expression with a back reference to group 1
    String patternStr = "<(\\S+?).*?>(.*?)</\\1>";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher("");

    // Set the input
    matcher.reset("test this is test xx <tag a=b> yy test test</tag> zz");

    // Get tagname and contents of tag
    boolean matchFound = matcher.find();
    System.out.println(matchFound);
    String tagname = matcher.group(1); 
    System.out.println(tagname);//  w  w w .  j a  v a  2  s  . c om
    String contents = matcher.group(2); 
    System.out.println(contents);

    matcher.reset("xx <tag> yy </tag0>");
    matchFound = matcher.find(); 
  }
}

Result


Related Tutorials