In my program I will be reading a java file line by line, and if there is any string literal in that line, i will replace it with (say) \"ABC\".
Is there any
Based on Uri's answer of using the parser grammar in this question:
"(?:\\[\\'"tnbfru01234567]|[^\\"])*?"
as Java string:
"\"(?:\\\\[\\\\'\"tnbfru01234567]|[^\\\\\"])*?\""
Explanation (see also Java String escape sequences):
" // start with a double quote
(?: // a non-capture group
\\[\\'"tnbfru01234567] // either an escape sequence
| // or
[^\\"] // not an escape sequence start or ending double quote
)*? // zero or more times, not greedy
" // ending double quote
Example (jlordo's solution fails on this):
String literal = "String foo = \"\\\\\" + \"bar\" + \"with\\\"escape\" + \"baz\" + \"\\117\\143\\164\\141\\154\";";
String regex = "\"(?:\\\\[\\\\'\"tnbfru01234567]|[^\\\\\"])*?\"";
String replacement = "\"\"";
String wanted = literal.replaceAll(regex, replacement);
System.out.println(literal);
System.out.println(wanted);