用Java中的等效字符替换HTML代码 [英] Replace HTML codes with equivalent characters in Java
问题描述
目前我正在努力在java中转换具有等效字符的HTML代码。
我需要将以下代码转换为字符。
Currently I'm working on converting HTML codes with equivalent characters in java. I need to convert the below code to characters.
è - è
® - ®
& - &
ñ - ñ
& - &
我尝试使用正则表达式模式
I tried using the regex pattern
(&#x)([\\d|\\w]*)([\\d|\\w]*)([\\d|\\w]*)([\\d|\\w]*)(;)
当我调试时, matcher.find()
给我 true
但是控件跳过我编写转换代码的循环。不知道那里发生了什么。
When I debug, matcher.find()
gives me true
but the control skips the loop where I have written the code for conversion. Don't know what is happening there.
另外,有没有办法优化这个正则表达式?
Also, is there any way to optimize this regex?
任何帮助都表示赞赏。
异常
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 。阿帕奇.org / lang /> Apache commons lang :
Yes, don't use regex for this task, use Apache StringEscapeUtils from Apache commons lang:
import org.apache.commons.lang.StringEscapeUtils;
...
String withCharacters = StringEscapeUtils.unescapeHtml(yourString);
JavaDoc说:
将包含实体转义的字符串Unescapes转换为包含
字符串的字符串,该字符串对应于转义符。支持
HTML 4.0实体。
Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.
例如,字符串& lt; Fran& ccedil; ais& gt;
将变为<Français>
如果实体无法识别,则为单独留下,并逐字插入结果字符串。例如& gt;& zzzz; x
将变为>& zzzz; x
。
If an entity is unrecognized, it is left alone, and inserted verbatim into the result string. e.g. ">&zzzz;x"
will become ">&zzzz;x"
.
这篇关于用Java中的等效字符替换HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!