Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly match a Java string literal [duplicate]

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.

like image 244
Tiago Veloso Avatar asked Jun 02 '10 14:06

Tiago Veloso


People also ask

What is difference between matches () and find () in Java regex?

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.

How do you replace a string literal in Java?

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).


2 Answers

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.

like image 121
Wangnick Avatar answered Oct 23 '22 06:10

Wangnick


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

like image 41
Hachi Avatar answered Oct 23 '22 06:10

Hachi