我需要对字符串中的所有引号(')进行转义,因此它变成\'

我尝试使用replaceAll,但是它什么也没做。由于某种原因,我无法使正则表达式正常工作。

我正在尝试

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

我真的被困在这里,希望有人能在这里帮助我。

谢谢,

我要

最佳答案

您必须先转义反斜杠,因为它是一个文字(yielding \\),然后再由于正则表达式(yielding \\\\)而再次转义。因此,请尝试:

 s.replaceAll("'", "\\\\'");

输出:
You\'ll be totally awesome, I\'m really terrible

关于java - Java:替换所有 ' in a string with\',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20556101/

10-12 17:38