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.
Difference between matches() and find() in Java RegexThe matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.
With replace() , you can replace an occurrence of a Character or String literal with another Character or String literal. You might use the String. replace() method in situations like: Replacing special characters in a String (eg, a String with the German character ö can be replaced with oe).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With