Regex to replace all string literals in a Java file

前端 未结 4 1945
广开言路
广开言路 2020-12-12 01:24

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

4条回答
  •  醉酒成梦
    2020-12-12 02:10

    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);
    

提交回复
热议问题