正确匹配 Java 字符串文字
我正在寻找一个正则表达式来匹配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");
类似这样的东西。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好的。那么您想要的是在字符串中搜索以双引号开头和结尾的字符序列?
请注意非贪婪的
.*?
模式。Ok. So what you want is to search, within a String, for a sequence of characters starting and ending with double-quotes?
Note the non-greedy
.*?
pattern.这个正则表达式也可以处理双引号(注意:perl扩展语法):
它定义每个“必须有奇数的转义\,然后
才可能对其进行美化,但它以这种形式工作
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
您可以查看 Java 的不同解析器生成器,以及它们的 StringLiteral 语法元素的正则表达式。
以下是来自 ANTLR 的示例:
You can look at different parser generators for Java, and their regular expression for the StringLiteral grammar element.
Here is an example from ANTLR:
您没有说明您使用什么工具来进行查找(perl?sed?文本编辑器ctrl-F 等)。但一般的正则表达式是:
编辑:这是一个快速的&肮脏的答案,并且不能处理转义的引用、评论等
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