Properly match a Java string literal [duplicate]

一世执手 提交于 2019-11-28 00:41:42

问题


This question already has an answer here:

  • Regex to replace all string literals in a Java file 4 answers

I am looking for a Regular expression to match string literals in Java source code.

Is it possible?

private String Foo = "A potato";
private String Bar = "A \"car\"";

My intent is to replace all strings within another string with something else. Using:

String A = "I went to the store to buy a \"coke\"";
String B = A.replaceAll(REGEX,"Pepsi");

Something like this.


回答1:


Ok. So what you want is to search, within a String, for a sequence of characters starting and ending with double-quotes?

    String bar = "A \"car\"";
    Pattern string = Pattern.compile("\".*?\"");
    Matcher matcher = string.matcher(bar);
    String result = matcher.replaceAll("\"bicycle\"");

Note the non-greedy .*? pattern.




回答2:


this regex can handle double quotes as well (NOTE: perl extended syntax):

"
[^\\"]*
(?:
    (?:\\\\)*
    (?:
        \\
        "
        [^\\"]*
    )?
)*
"

it defines that each " has to have an odd amount of escaping \ before it

maybe it's possible to beautify this a bit, but it works in this form




回答3:


You can look at different parser generators for Java, and their regular expression for the StringLiteral grammar element.

Here is an example from ANTLR:

StringLiteral
    :  '"' ( EscapeSequence | ~('\\'|'"') )* '"'
    ;



回答4:


You don't say what tool you're using to do your finding (perl? sed? text editor ctrl-F etc etc). But a general regex would be:

\".*?\"

Edit: this is a quick & dirty answer, and doesn't cope with escaped quotes, comments etc



来源:https://stackoverflow.com/questions/2958825/properly-match-a-java-string-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!