import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?: # non-capture group (repeat)\n"
+ " (?| # branch reset for group 1\n"
+ " ([^)(><\\n])| # either non-bracket... or:\n"
+ " <(?=.*(>))| # if < open angle capture > to group 1\n"
+ " >(?=.*(<))| # if > capture opening < to group 1\n"
+ " \\((?=.*(\\)))| # same for (), if ( capture ) to group 1\n"
+ " \\)(?=.*(\\()) # if ) catpure ( to group 1\n"
+ " )(?=.*((?(2)\\1\\2|\\1))$) # cond (2): if not outer chr (fwd ref)\n"
+ ")*? # as few as possible (lazy) / eof non-cap\n"
+ "[^)(><\\n]? # the middle character (no parens)\n"
+ "\\2$ # the right part (group 2 capture)";
final String string = "(_)tar<>rat(_)\n"
+ ")()_<(*&bab&*)>_()(\n"
+ ")(*?*)(\n"
+ "()<_<oxxo>_>()\n"
+ "<__>w(owiwo)w<__>\n"
+ "a(t<()((<oyo>))()>t)a\n\n"
+ "v\n\n"
+ "(_)tar<>rap(_)\n"
+ ")()_<(*&bab&*)>_))(\n"
+ ")(*?*)(.\n"
+ "()<-<oxxo>_>()\n"
+ "<__>w(ow(wo)w<__>\n"
+ "at<()((<oyo>))()>t)a";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
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