java - 用 Java 中的等效字符替换 HTML 代码

标签 java pattern-matching matcher

<分区>

目前我正致力于将 HTML 代码转换为 java 中的等效字符。 我需要将以下代码转换为字符。

&#x00E8; - è
&#xAE;   - ®
&#x0026; - &
&#x00F1; - ñ
&#x26;   - &

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

(&#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)

最佳答案

Also, is there any way to optimize this regex?

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

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

JavaDoc 说:

Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.

For example, the string "&lt;Fran&ccedil;ais&gt;" will become "<Français>"

If an entity is unrecognized, it is left alone, and inserted verbatim into the result string. e.g. "&gt;&zzzz;x" will become ">&zzzz;x".

关于java - 用 Java 中的等效字符替换 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14998726/

相关文章:

java - 从中缀表达式转换为后缀表达式后表达式之间的正确间距

javascript - 当字符串包含 2 个非连续的正斜杠(负向前瞻)时,正则表达式返回 false

Haskell 模式匹配 "diverge"和 ⊥

java - 如何在匹配器组而不是整个模式上追加替换?

java - Mockito Matchers isA、any、eq 和 same 有什么区别?

java - 程序运行,只得到空值作为返回值

java - 无法启动jBoss AS 7.1

java - 使用 ViewModel 仅在用户干预时调用

python - opencv 特征与空公式模板匹配

python - 匹配器正在返回一些重复项