Regex to replace all string literals in a Java file

前端 未结 4 1937
广开言路
广开言路 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:13

    Consider the following regular expression:

    String regex = "\"(?:\\\\\"|[^\"])*?\"";
    

    It starts with a quote, followed by zero or more non-quote characters or escaped quote characters. The last character has to be a quote.

    If you apply this regex to java code, remember that it also matches text inside quotes in comments. If you have unbalanced quotes in your comments it won't match string literals (it will then match the exact opposite).

    If you had the example you posted in a String variable named example the following would work:

    String wanted = example.replaceAll(regex, "\"ABC\"");
    

    Here's a full example:

    String literal = "String foo = \"bar\" + \"with\\\"escape\" + \"baz\";";
    String regex = "\"(?:\\\\\"|[^\"])*?\"";
    String replacement = "\"\"";
    String wanted = literal.replaceAll(regex, replacement);
    System.out.println(literal);
    System.out.println(wanted);
    

    prints

    String foo = "bar" + "with\"escape" + "baz";
    String foo = "" + "" + "";
    

提交回复
热议问题