Determining if a Group is in the Path with Regular expressions

Introduction

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.