取消转义和转换字符串编码 [英] Unescape and convert string encoding
问题描述
我得到的字符串跟随模式
MMM d yyyy HH:mm:ss z
,区域设置为法语
。 由于法语口音的编码,日期在二月,八月或十二月期间出现问题。例如,我得到 dé c。 15 2011年16:55:38 CET
2011年12月15日。
我无法更改字符串的创建方式,所以我必须处理我身边的错误编码。似乎当生成的字符串被严重编码(UTF-8内容编码为ISO 8859-1)然后escapde。
现在我使用:
stringFromXML = stringFromXML.replaceAll(é,é);
stringFromXML = stringFromXML.replaceAll(û,û);
它的作品是因为法语月份的唯一口音是é
和û
但是是否有一个更简洁的方法来解码和转换字符?
您需要两个步骤:
-
解决数字字符引用,例如使用
String / E code,如Andy所建议的:
String unescaped = StringEscapeUtils.unescapeHtml(in);
-
通过将字符视为UTF-8代码单元来修正编码:
String out = new String(unescaped.getBytes(ISO-8859-1),UTF-8);
I have to parse a String to a Date object in Java.
The string I get following the pattern MMM d yyyy HH:mm:ss z
with locale set to French
.
The problem occures when the date is in february, august or december due to encoding of french accents. For example, I get déc. 15 2011 16:55:38 CET
for december 15th 2011.
I can't change the way the string is created so I have to deal with the bad encoding on my side. It seems that when generated the string is badly encoded (UTF-8 content encoded as ISO 8859-1) then escapde.
For now I use :
stringFromXML = stringFromXML.replaceAll("é", "é");
stringFromXML = stringFromXML.replaceAll("û", "û");
It works because the only accent in french month are é
and û
but is there a cleaner way to unescape and convert characters?
You need two steps:
Resolve numeric character references, for example, using
StringEscapeUtils
as suggested by Andy:String unescaped = StringEscapeUtils.unescapeHtml(in);
Fix encoding by treating characters as UTF-8 code units:
String out = new String(unescaped.getBytes("ISO-8859-1"), "UTF-8");
这篇关于取消转义和转换字符串编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!