替换不是替换 Java 中的双引号 [英] Replace is not replacing double quotes in java

查看:48
本文介绍了替换不是替换 Java 中的双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自应用程序的以下字符串:

I have a below string which is coming from the application:

Hotel "Lowest Rate Guaranteed" Terms and Conditions

我正在尝试使用以下行替换上述语句中的双引号:

I am trying to replace double quotes in the above statement using following line:

Tempdata = Tempdata.replace("\"", "");
System.out.println(Tempdata);

它不起作用并且总是返回相同的值,但是如果我手动删除上面的双引号并手动输入双引号并尝试相同的命令,它可以正常工作.

It's not working and always returning the same value but if I manually remove the above double quote and enter the double quote manually and try the same command, it works fine.

手动替换双引号后,字符串如下

After replacing the double quote manually, the string looks like

Hotel "Lowest Rate Guaranteed" Terms and Conditions

我们可以看到双引号有细微的差别.看起来来自应用程序的双引号是 utf-8.

We can see there is minor difference in the double quote. Look like the double quote which is coming from application is utf-8.

感谢任何帮助.谢谢

推荐答案

你可以把双引号复制到replace中,对应的代码是\u201c\u201d.

You could just copy the double quotes into the replace, the respective codes are \u201c and \u201d.

或者,您可以使用正则表达式,例如 [\"'\u2018\u2019\u201c\u201d] 来匹配所有引号.(但是这些字符经常被误用作引号.我'我看着你,严肃而尖锐")

Alternatively you could use a regular expression such as [\"'\u2018\u2019\u201c\u201d] to match all quotes. (Not however those characters often misused as quotation marks. I'm looking at you, `grave and acute´)

哪里

  • " 匹配 "
  • ' 匹配 '
  • \u2018 匹配(左单引号)
  • \u2019 匹配 '(右单引号)
  • \u201c 匹配(左双引号)
  • \u201d 匹配 "(右双引号)
  • " matches "
  • ' matches '
  • \u2018 matches (left single quotation mark)
  • \u2019 matches (right single quotation mark)
  • \u201c matches " (left double quotation mark)
  • \u201d matches " (right double quotation mark)

一个例子可能是使用 String.replaceAll():

An example of this could be just using String.replaceAll():

tempdata = tempdata.replaceAll("[\"'\u2018\u2019\u201c\u201d]", "")

或者,如果您需要经常这样做,编译模式并保存会更高效:

Or, if you need to do this often, compiling the pattern and saving is more efficient:

在你班级的某个地方:

private final Pattern quotation = Pattern.compile("[\"'\u2018\u2019\u201c\u201d]") 

然后再往下:

quotation.matcher(tempdata).replaceAll("")

在一个不相关的说明中,不要在 Java 中给变量大写名称,它会灼伤我的眼睛并且违反所有常见的约定.给它们起与类相同的名称是非常邪恶的.

On an unrelated note, don't give variables capital names in Java, it burns my eyes and is against all common convention. Giving them the same name as a class is extra evil.

这篇关于替换不是替换 Java 中的双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆