import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?:\\/\\/(?:\\\\\\n|[^\\n])*\\n)|(?:\\/\\*[\\s\\S]*?\\*\\/)|((?:R\"([^(\\\\\\s]{0,16})\\([^)]*\\)\\2\")|(?:@\"[^\"]*?\")|(?:\"(?:\\?\\?'|\\\\\\\\|\\\\\"|\\\\\\n|[^\"])*?\")|(?:'(?:\\\\\\\\|\\\\'|\\\\\\n|[^'])*?'))";
final String string = "// /*\n\n\n"
+ "/*\n"
+ " This is a multi line comment\n\n"
+ "// <- ignored since in a comment */\n\n"
+ "// \"abc\" word \"\n\n"
+ "// This is a single line comment\n\n\n"
+ "char cha1[] = \"This is a string containing a combination //\",\n"
+ " cha2[] = \"This has /* a fake comment */ in it\",\n"
+ " cha3[] = \"This is tough because of (ignore this //) \\\n"
+ "line continueation\",\n"
+ " cha4[] = \"Handle comments in strings with \\\" escaped quotes\\\n"
+ "and escaped escaped escapes \\\\\";\n\n\n"
+ "// This is a single line comment \\\n"
+ "continuing on the next line\n\n\n"
+ "void main()\n"
+ "{\n"
+ " int chInt = '\\\\b\\'';\n\n"
+ " printf(\"Hello world!\");\n\n"
+ " cpp11_1(R\"xy(\"/**/)xy\");\n"
+ " cpp11_2(R\"(\"/**/)\");\n"
+ " cS(@\"End at the right place\\\" /*and ignore this */);\n\n"
+ " return 0;\n"
+ "}\n";
final String subst = "\\1";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
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