Java:用\'替换字符串中的所有' [英] Java: Replace all ' in a string with \'
本文介绍了Java:用\'替换字符串中的所有'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在字符串中转义所有引号('),因此它变为\'
I need to escape all quotes (') in a string, so it becomes \'
我尝试过使用replaceAll,但它没有做任何东西。出于某种原因,我无法使正则表达式工作。
I've tried using replaceAll, but it doesn't do anything. For some reason I can't get the regex to work.
我正在尝试
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.
谢谢,
Iwan
推荐答案
你必须首先转义反斜杠,因为它是一个文字(产生 \\
),然后因为正则表达式再次转义它(产生 \\\\
)。所以,试试:
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("'", "\\\\'");
输出:
You\'ll be totally awesome, I\'m really terrible
这篇关于Java:用\'替换字符串中的所有'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文