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?
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
The replaceAll() method is similar to the String. replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string.
Double quotes characters can be escaped with backslash( \ ) in java.
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
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.
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