Properly match a Java string literal [duplicate]
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
精彩评论