Regex to replace all string literals in a Java file

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

    s = s.replaceAll("\"([^\n\"\\]+|\\\\.)*\"", "\"ABC\"");
    

    This searches quote, and any either non-quotes/non-backslahes/non-linefeeds or backslash+character, till quote.

    \"
      (
        [^\n\"\\]+
      |
        \\\\.
      )*
    \"
    
    • [^ ... ] non of the enclosed chars, range possible too A-Z.
    • | or.
    • . any character, by default not line endings.
    • ... + one or more of ... .
    • ... * zero or more of ... .

提交回复
热议问题