Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Replace all ' in a string with \'

Tags:

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

like image 293
Iwan Eising Avatar asked Dec 12 '13 23:12

Iwan Eising


People also ask

How do I replace an entire string with another string in Java?

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.

How do you replace all occurrences of a character in a string?

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.

How do you replace all special characters in a string in Java?

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.

What is replaceAll \\ s in Java?

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.


1 Answers

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 
like image 55
Sage Avatar answered Sep 28 '22 16:09

Sage