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?
replaceAlluses regular expressions – in which the backslash just escapes the next character, even in the replacement.Use
replaceinstead and it’s fine… or you can double the backslash in the second argument if you want to use the regular expression form: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
Stringto use regular expressions to start with – things likefoo.split(".")which will split on every character rather than on periods, completely unexpectedly to the unwary developer.