17

目前我正在用java中的等效字符转换HTML代码。我需要将下面的代码转换为字符。

è - è
®   - ®
& - &
ñ - ñ
&   - &

我尝试使用正则表达式模式

(&#x)([\\d|\\w]*)([\\d|\\w]*)([\\d|\\w]*)([\\d|\\w]*)(;)

当我调试时,matcher.find()给了我,true但控件跳过了我编写转换代码的循环。不知道那里发生了什么。

另外,有没有办法优化这个正则表达式?

任何帮助表示赞赏。

例外

java.lang.NumberFormatException: For input string: "x26"
      at java.lang.NumberFormatException.forInputString(Unknown Source)
      at java.lang.Integer.parseInt(Unknown Source)
      at java.lang.Integer.parseInt(Unknown Source)
      at org.apache.commons.lang.Entities.unescape(Entities.java:683)
      at org.apache.commons.lang.StringEscapeUtils.unescapeHtml(StringEscapeUtils.java:483)
4

2 回答 2

33

另外,有没有办法优化这个正则表达式?

是的,不要对这个任务使用正则表达式,使用来自Apache commons lang的 Apache StringEscapeUtils

import org.apache.commons.lang.StringEscapeUtils;
...
String withCharacters = StringEscapeUtils.unescapeHtml(yourString);

JavaDoc 说:

将包含实体转义的字符串取消转义为包含与转义对应的实际 Unicode 字符的字符串。支持 HTML 4.0 实体。

例如,字符串"&lt;Fran&ccedil;ais&gt;"将变为"<Français>"

如果一个实体无法识别,则将其单独放置,并逐字插入结果字符串中。例如"&gt;&zzzz;x"将成为">&zzzz;x".

于 2013-02-21T09:34:20.447 回答
3

所有其他可能性或现有util方法之一可能是 spring-web 的org.springframework.web.util.HtmlUtils.htmlUnescape.

自包含 Groovy 脚本中的示例用法:

@Grapes(
    @Grab(group='org.springframework', module='spring-web', version='4.3.0.RELEASE')
)
import org.springframework.web.util.HtmlUtils

println HtmlUtils.htmlUnescape("La &#xE9;lite del tenis no teme al zika y jugar&#xE1; en R&#xED;o")
于 2016-06-25T19:03:27.187 回答