import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "<div\\s+class=\"asd\"> # match an opening 'div' with an id that starts with 't' and some digits\n"
+ "[^<>]* # match zero or more chars other than '<' and '>'\n"
+ "( # open group 1\n"
+ " <div[^>]*> # match an opening 'div'\n"
+ " (?: # open a non-matching group\n"
+ " [^<>]* # match zero or more chars other than '<' and '>'\n"
+ " | # OR\n"
+ " (?1) # recursively match what is defined by group 1\n"
+ " )* # close the non-matching group and repeat it zero or more times\n"
+ " </div> # match a closing 'div'\n"
+ ") # close group 1\n"
+ "[^<>]* # match zero or more chars other than '<' and '>'\n"
+ "</div> ";
final String string = "<div>\n"
+ " <div class=\"asd\">\n"
+ " <div>\n"
+ " <div>\n"
+ " Hello\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ "</div>";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html