正确匹配Java字符串文字 [英] Properly match a Java string literal

查看:102
本文介绍了正确匹配Java字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有可能吗?

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");

这样的事情。

推荐答案

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

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\"");

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

这篇关于正确匹配Java字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆