import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?s) *(<sample [^>]*>.*?<\\/ ?sample>)";
final String string = "<!DOCTYPE qhelp PUBLIC\n"
+ " \"-//Semmle//qhelp//EN\"\n"
+ " \"qhelp.dtd\">\n"
+ "<qhelp>\n\n\n"
+ "<overview>\n"
+ "<p>The C++ <code>throw</code> expression can take several forms. One form throws a new exception, whereas the\n"
+ "other re-throws the current exception. In the latter case, if there is no current exception, then the program\n"
+ "will be terminated. Presence of a re-throw outside of an exception handling context is often caused by the\n"
+ "programmer not knowing what kind of exception to throw.</p>\n\n"
+ "</overview>\n"
+ "<recommendation>\n"
+ "<p>The <code>throw</code> expression should be changed to throw a particular type of exception.</p>\n\n"
+ "</recommendation>\n"
+ "<example>\n"
+ "<sample language=\"cpp\">\n"
+ "void bad() {\n"
+ " /* ... */\n"
+ " if(error_condition)\n"
+ " throw;\n"
+ "}\n\n"
+ "void good() {\n"
+ " /* ... */\n"
+ " if(error_condition)\n"
+ " throw std::exception(\"Something went wrong.\");\n"
+ "}\n"
+ "</sample>\n\n"
+ "</example>\n"
+ "<references>\n\n"
+ " <li>Open Standards: <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf\">Standard for Programming Language C++, draft n3337</a> [except.throw], clause 9, page 380.</li>\n\n\n"
+ "</references>\n"
+ "</qhelp>";
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