Tag Archives: Backreference

Determining if a Group is in the Path with Regular expressions


Note: See this article about working with Regular Expressions.

// 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("xx <tag a=b> yy </tag> zz");j

// Get tagname and contents of tag
boolean matchFound = matcher.find();   // true
String tagname = matcher.group(1);     // tag
String contents = matcher.group(2);    //  yy

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