首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java:将字符串中的all‘替换为\’

Java:将字符串中的all‘替换为\’
EN

Stack Overflow用户
提问于 2013-12-13 07:05:25
回答 2查看 117.1K关注 0票数 24

我需要转义字符串中的所有引号('),这样它就变成了\‘

我试过使用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

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

谢谢,

Iwan

EN

回答 2

Stack Overflow用户

发布于 2013-12-13 07:09:35

您还可以尝试使用像StringEscapeUtils这样的工具来让您的工作更轻松:http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

s = StringEscapeUtils.escapeJava(s);
票数 1
EN

Stack Overflow用户

发布于 2020-04-08 23:26:38

可以使用apache的commons-text库(而不是commons-lang):

示例代码:

org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);

依赖关系:

compile 'org.apache.commons:commons-text:1.8'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.8</version>
</dependency>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20556101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档