正确匹配Java字符串文字

时间:2010-06-02 14:49:55

标签: java regex literals string-literals

我正在寻找一个正则表达式来匹配Java源代码中的字符串文字。

有可能吗?

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

我的意图是用其他东西替换另一个字符串中的所有字符串。使用:

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

像这样。

5 个答案:

答案 0 :(得分:4)

确定。那么你想要的是在一个字符串中搜索以双引号开头和结尾的字符序列?

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

请注意非贪婪的.*?模式。

答案 1 :(得分:2)

这个正则表达式也可以处理双引号(注意:perl扩展语法):

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

它定义每个“必须在它之前有一个奇数的转义\

也许有可能美化这一点,但它以这种形式运作

答案 2 :(得分:1)

您可以查看Java的不同解析器生成器,以及StringLiteral语法元素的正则表达式。

这是example from ANTLR

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

答案 3 :(得分:-1)

你没有说你用什么工具来做你的发现(perl?sed?文本编辑器ctrl-F等等)。但一般的正则表达式是:

\".*?\"

编辑:这是一个快速的&肮脏的回答,并没有应对逃脱的报价,评论等

答案 4 :(得分:-1)

使用此:

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

使用

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

产生以下'B'

I went to the store to buy a Pepsi and a box of Pepsi
相关问题