I need to escape all quotes (') in a string, so it becomes \'
I've tried using replaceAll, but it doesn't do anything. For some reason I can't get the regex to work.
I'm trying with
String s = "You'll be totally awesome, I'm really terrible"; String shouldBecome = "You\'ll be totally awesome, I\'m really terrible"; s = s.replaceAll("'","\\'"); // Doesn't do anything s = s.replaceAll("\'","\\'"); // Doesn't do anything s = s.replaceAll("\\'","\\'"); // Doesn't do anything
I'm really stuck here, hope somebody can help me here.
Thanks,
Iwan
To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
Using String.String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex. There are two overloaded methods available in Java for replace() : String. replace() with Character, and String.
The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.
You have to first escape the backslash because it's a literal (yielding \\
), and then escape it again because of the regular expression (yielding \\\\
). So, Try:
s.replaceAll("'", "\\\\'");
output:
You\'ll be totally awesome, I\'m really terrible
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