Reputation:
How do I find out all of the strings surrounded with double quote "
and replace them a new string?
Input Output
----- ------
`Hello "User", what's up?` -> `Hello l("User"), what's up?`
`Regexes are "so complex"` -> `Regex are l("so complex")`
how do I do this in Java?
Upvotes: 1
Views: 892
Reputation: 33928
Look for ("[^"\n]+")
, replace with l($1)
:
str = str.replaceAll("(\"[^\"\n]+\")", "l($1)");
If you want to allow backslash escapes in the quotes, like "These are \"Nested\" quotes"
you could use an expression like this:
("(?:[^"\\\n]|\\.)*")
Used in Java like so:
str = str.replaceAll("(\"(?:[^\"\\\\\n]|\\\\.)*\")", "l($1)");
Upvotes: 3
Reputation: 17188
You've basically got one issue, twice. You're trying to put things (*
and \w
) into the character class that don't belong inside those brackets. You've found the predefined character class (\w
) already, so you can just use it directly:
"\w*" // These would be nested quotes, and I'm omitting escapes for clarity
This is equivalent to: "[a-zA-Z_0-9]*"
When you're doing your replacement, you'll need to capture the match, so use parentheses to make a capturing group. The example below should work for your needs (including escapes and so on).
String bro = "Hello \"bro\", what's \"up\"?";
String replaced = bro.replaceAll("(\"\\w*\")", "l($1)");
System.out.println(replaced); // prints: Hello l("bro"), what's l("up")?
If you want to capture spaces and punctuation within quotes rather than only single, unpunctuated words, you could just replace \\w
with a character class that contains the characters you care about. Tweak it to the specific needs of your operation. If you don't want to discriminate at all on the content, you could use [^\"]
(note the need to escape the "
) to match any non-doublequote character:
String bro = "Hello \"bro\", \"what's up\"?";
String replaced = bro.replaceAll("(\"[^\"]*\")", "l($1)");
System.out.println(replaced); // prints: Hello l("bro"), l("what's up")?
Upvotes: 1
Reputation: 3190
Try this :
String newValue=oldValue.replaceAll("\"([^\"]*?)\"", "(\"$1\")");
Upvotes: 2