【问题标题】:I can't get replace / replaceAll to work我无法让 replace / replaceAll 工作
【发布时间】:2013-11-28 04:02:59
【问题描述】:

我需要显示应该显示的数据库中的数据:

in the html: Behälter
in the browser: Behälter

但相反,我得到了这样的数据:

in the html: Behälter
in the browser: Behälter

所以我需要将& 改回&。我使用 Java 的 String 类中的 replaceAll 和 replace 方法。但它没有用。我什至使用 indexOf 方法检查字符串是否有 & ,但它似乎没有捕捉到甚至看到 & 符号。

我的代码:

// supposed the value returned by the getObject function is "Behälter"
String text = (String)getObject("value");

if (text.indexOf("&") >= 0) text = "abc" + text;

text = text.replace("&", "&");
text = text.replaceAll("&", "&");

if (text.indexOf("&") >= 0) text = text + "def";
text = text + "xyz";

结果是

in the html: Behälterxyz
in the browser: Behälterxyz

我输入和使用 replace/replaceAll 的方式有什么问题吗?谢谢你的回答。

【问题讨论】:

  • 是的。我想如果替换&符号,浏览器将自动在其 unicode 字符对应物中显示 ä 字符。但是当我查看页面源时,ä 字符仍然写为ä,而不是ä

标签: java string replace replaceall


【解决方案1】:

我建议对 StringEscapeUtils.unescapeHtml() 使用 Apache Commons Lang

用编码字符输入你的字符串,它应该把它解码出来。

【讨论】:

  • 一开始我不想用这种依赖外部库的方案,因为我的开发环境有点不一样。所以我不知道我是否可以像往常一样导入任何外部库。但后来我试了一下,我不仅可以导入和使用这个库,而且效果还不错!谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-12-26
  • 2014-03-08
  • 2018-10-10
  • 2016-09-02
  • 2015-05-20
  • 2015-10-22
  • 2023-03-24
  • 2017-11-13
相关资源
最近更新 更多