Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.replaceAll doesn't replace a quote with escaped quote

Tags:

java

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?

like image 303
frosty Avatar asked Aug 26 '11 06:08

frosty


People also ask

Does replaceAll change the string?

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.

What is the difference between Replace () and replaceAll ()?

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.

How do you escape a quote from a string in Java?

Double quotes characters can be escaped with backslash( \ ) in java.

What is replaceAll \\ s in Java?

Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.


1 Answers

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.

like image 194
Jon Skeet Avatar answered Oct 27 '22 23:10

Jon Skeet