import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?:\\n+|\\A)?\n"
+ "(?<code_all>\n"
+ " (?<code_start>\n"
+ " [ ]{0,3}\n"
+ " (?:\n"
+ " (?<with_backtick>[`]{3,})\n"
+ " |\n"
+ " (?<with_tilde>[~]{3,})\n"
+ " )\n"
+ " )\n"
+ " [ \\t]*\n"
+ " (?(<with_tilde>)\n"
+ " (?:\n"
+ " (?:\n"
+ " (?:\n"
+ " (?<code_class>(?&_code_class))\n"
+ " (?:\n"
+ " [ \\t]*\n"
+ " \\{[[:blank:]\\h]*(?<code_attr>(?&_code_attr))[[:blank:]\\h]*\\}\n"
+ " )?\n"
+ " )\n"
+ " |\n"
+ " (?:\n"
+ " \\{[[:blank:]\\h]*(?<code_attr>(?&_code_attr))[[:blank:]\\h]*\\}\n"
+ " )\n"
+ " )?\n"
+ " )\n"
+ " |\n"
+ " (?:\n"
+ " (?:\n"
+ " (?<code_class>(?&_code_class))\n"
+ " (?:\n"
+ " [ \\t]*\n"
+ " \\{[[:blank:]\\h]*(?<code_attr>(?&_code_attr))[[:blank:]\\h]*\\}\n"
+ " )?\n"
+ " )\n"
+ " |\n"
+ " (?:\n"
+ " \\{[[:blank:]\\h]*(?<code_attr>(?&_code_attr))[[:blank:]\\h]*\\}\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " \\n+\n"
+ " (?<code_content>.*?)\n"
+ " \\n+\n"
+ " (?<!`)\n"
+ " \\g\\{code_start\\}\n"
+ " (?!`)\n"
+ " [ \\t]*\n"
+ " (?:\\n|\\Z)\n"
+ ")\n"
+ "(?<code_trailing_new_line>\\n|\\Z)\n"
+ "(?(DEFINE)\n"
+ " (?<_code_class> [\\w\\-\\.]+)\n"
+ " (?<_code_attr> [^\\}]+)\n"
+ ")";
final String string = "``` .html\n"
+ "<ul>\n"
+ " <li>Code block first in file</li>\n"
+ " <li>doesn't work under some circumstances</li>\n"
+ "</ul>\n"
+ "```\n\n"
+ "`````` .html {#codeid}\n"
+ "</div>\n"
+ "``````\n\n\n"
+ "~~~ .html\n"
+ "<ul>\n"
+ " <li>Code block first in file</li>\n"
+ " <li>doesn't work under some circumstances</li>\n"
+ "</ul>\n"
+ "~~~\n\n"
+ "~~~\n"
+ "<div>\n"
+ "~~~\n"
+ "~~~\n"
+ "<div>\n"
+ "~~~\n\n"
+ "~~~\n"
+ "<div>~~~</div>\n"
+ "~~~\n\n"
+ "~~~\n"
+ "<p>```\n"
+ "```\n"
+ "<p>```\n"
+ "~~~\n\n"
+ "~~~\n"
+ "Some text\n\n"
+ " Indented code block sample code\n"
+ "~~~\n\n"
+ "~~~~\n"
+ "In code block\n"
+ "~~~\n"
+ "Still in code block\n"
+ "~~~~~\n"
+ "Still in code block\n"
+ "~~~~\n\n"
+ "~~~~~ .html {#codeid}\n"
+ "</div>\n"
+ "~~~~~\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL | 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