Reputation: 21762
Having a hard time replacing a quote with an escaped quote. I have a string that has the value of 'Foo "bar" foobar', and I am trying to replace the quotes around bar with escaped quotes, and it isn't working. I am going crazy.
s=s.replaceAll("\"","\\\"");
I would expect s to have the value of 'foo \"bar\" foobar', but it doesn't. Any help?
Upvotes: 16
Views: 22191
Reputation: 1106
String str = "'Foo \"Bar\" Bar'";
System.out.println(str);
System.out.println(str.replaceAll("\"", "\\\\\""));
Upvotes: 1
Reputation: 120811
You need to escape both replace all arguments because they are regex!
@Test
public void testReplace() {
assertEquals("foo\\\"bar\\\"",
"foo\"bar\"".replaceAll("\\\"", "\\\\\\\""));
}
So if you want to write "
you need to escape the regex -> \"
but because you are in java you need to escape the \
and "
for java to, so you get \\\\"
. (that is the search parameter).
For the replace parameter you want to have \"
-> in regex: \\\"
-> in Java \\\\\\\"
Upvotes: 3
Reputation: 9478
please follow below program and use > s.replace("/"."//");
public class stringbackslash {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="\";
s=s.replace("\", "\\");
System.out.println(s);
}
}
Upvotes: 0
Reputation: 14549
s=s.replaceAll("\"","\\\\\"");
But you should really go with replace(...)
as the others here advice.
Upvotes: 1
Reputation: 1500675
replaceAll
uses regular expressions - in which the backslash just escapes the next character, even in the replacement.
Use replace
instead and it's fine... or you can double the backslash in the second argument if you want to use the regular expression form:
String after = before.replaceAll("\"", "\\\\\"");
This could be useful if you need to match the input using regular expressions, but I'd strongly recommend using the non-regex form unless you actually need regex behaviour.
Personally I think it was a mistake for methods in String
to use regular expressions to start with - things like foo.split(".")
which will split on every character rather than on periods, completely unexpectedly to the unwary developer.
Upvotes: 28
Reputation: 597116
Use s = s.replace("\"", "\\\"");
, which is the non-regex version.
Upvotes: 12