Properly match a Java string literal [duplicate]

拈花ヽ惹草 提交于 2019-11-29 06:47:07

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

Use this:

String REGEX = "\"[^\"]*\"";

Tested with

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

Yields the following 'B'

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