Properly match a Java string literal [duplicate]

2020-02-11 04:05发布

问题:

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