import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\[(b|i|u|h1|h2|h3|large|small|list|table|grid)\\](?:((?!\\[\\/\\1\\]).)*?|(?R))*\\[\\/\\1\\]";
final String string = "[b]the problem is that my [i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u] [/b]\n"
+ "[i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u]\n\n"
+ "[a]ssss[a]sssss[/a]ss[/a]\n\n"
+ "[b]sss[/b]\n\n"
+ "[c]asdfasd[d]asdaf[/d]fasdf[/c]\n\n"
+ "[i]test test [i]as fd[/i]this should match the whole line[/i]\n\n"
+ "[i]test test[j]this should match the whole line[/j]test[/i]\n\n"
+ "[i] test [j]this should match the pair of 'i' tags and ignore the second 'j' tag [/i] [/j]\n\n"
+ "the below line should have three sets of matches: center, h3, and grid; it only matches the h3 and grid tags\n"
+ "[center][logo][/center][hr][hr][h3]header[/h3][/center][hr][hr][grid][row][cell][b]some label[/b][cell]: [date][/grid]\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (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