开发者

Properly match a Java string literal [duplicate]

开发者 https://www.devze.com 2023-01-01 18:16 出处:网络
This question already has answers here: Regex to replace all string literals in a Java file (4 answers)
This question already has answers here: Regex to replace all string literals in a Java file (4 answers) Closed 8 years ago.

I a开发者_运维知识库m 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.


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.


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


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 | ~('\\'|'"') )* '"'
    ;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消