import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?xsm) # free-spacing mode, DOTALL, multi-line\n"
+ "(?=.*?blue) # if blue isn't there, fail without delay\n\n"
+ "###### Recursive Section ######\n"
+ "# This section aims to balance empty lines with digits, i.e.\n"
+ "# emptyLine,emptyLine,emptyLine ... ~1~2~3\n"
+ "# The last digit block is captured to Group 2, e.g. ~3\n"
+ "(?= # lookahead\n"
+ "( # Group 1\n"
+ " (?: # skip one line that doesn't contain blue\n"
+ " ^ # start of line\n"
+ " (?:(?!blue)[^\\r\\n])* # zero or more chars not followed by blue\n"
+ " (?:\\r?\\n) # newline\n"
+ " ) \n"
+ " (?:(?1)|[^~]+) # recurse Group 1 OR match all non-tilde chars\n"
+ " (~\\d+) # match a sequence of digits\n"
+ ")? # End Group 1\n"
+ ") # End lookahead. \n\n"
+ "# Group 2, if set, now contains the number of lines skipped\n"
+ ".*? # lazily match chars up to... \n"
+ "blue # match blue\n"
+ ".*? # lazily match chars up to... \n"
+ "(?(2)\\2) # if Group 2 is set, match Group 2\n"
+ "~ # Match the next tilde\n"
+ "\\K # drop what was matched so far\n"
+ "\\d+ # match the next digits: this is the match \n";
final String string = "Paint it white\n"
+ "Paint it black\n"
+ "Why not blue?\n"
+ "Or red or brown?\n\n"
+ "~1~2~3~4~5~6~7~8~9~10";
final Pattern pattern = Pattern.compile(regex);
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