import re
regex = re.compile(r"(?:\/\/(?:\\\n|[^\n])*\n)|(?:\/\*[\s\S]*?\*\/)|((?:R\"([^(\\\s]{0,16})\([^)]*\)\2\")|(?:@\"[^\"]*?\")|(?:\"(?:\?\?'|\\\\|\\\"|\\\n|[^\"])*?\")|(?:'(?:\\\\|\\'|\\\n|[^'])*?'))")
test_str = ("// /*\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")
subst = "\\1"
result = regex.sub(subst, test_str)
if result:
print(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 Python, please visit: https://docs.python.org/3/library/re.html