將HTML中的特殊字元轉化為可顯示的字元
阿新 • • 發佈:2019-01-07
很多時候叢網頁中抽取的內容中都含有很多特殊的轉義字元,網頁中顯示的要麼是實體名稱,要麼是實體編碼,如
顯示 | 說明 | 實體名稱 | 實體編號 |
---|---|---|---|
半方大的空白 |   |   | |
全方大的空白 |   |   | |
不斷行的空白格 | |   | |
< | 小於 | < | < |
> | 大於 | > | > |
& | &符號 | & | & |
" | 雙引號 | " | " |
© | 版權 | © | © |
® | 已註冊商標 | ® | ® |
™ | 商標(美國) | ™ | ™ |
× | 乘號 | × | × |
÷ | 除號 | ÷ | ÷ |
原理是根據實體編碼中的數字,得到對應的字元。但上述方法不支援將實體名稱轉化為可顯示字元,如能將"""轉化為雙引號,卻不能識別"""。這次沒有固定的規律,只能自己作映射了。比較折中的做法是轉化如下幾個常見的:
> | > |
" | " |
  | |
' | ‘ |
/** * Convert HTML character enitities(Unicode) to part of a Java String */ import java.util.regex.*; public class UnicodeCeToJavaString { static final String mbs = "&#(\\d+);"; // like "ロ" public static String EncodeCesToChars(String paramStr) { paramStr = paramStr.replace("&","&") .replace("<","<") .replace(">",">") .replace(""","\"") .replace(" "," ") .replace("'","'"); String mbChar; StringBuffer sb = new StringBuffer(); Pattern pat = Pattern.compile(mbs); Matcher mat = pat.matcher(paramStr); while (mat.find()) { mbChar = getMbCharStr(mat.group(1)); // pass the digit part mat.appendReplacement(sb, mbChar); } mat.appendTail(sb); return new String(sb); } /* worker method */ static String getMbCharStr(String digits) { // handle "12525" part which is // a char[] cha = new char[1]; // Unicode value stringnized try { int val = Integer.parseInt(digits); char ch = (char) val; cha[0] = ch; } catch (Exception e) { System.err.println("Error from getMbCharStr:"); e.printStackTrace(System.err); } return new String(cha); // easy!, because Java uses Unicode } public static void main(String[] args) { System.out.println(UnicodeCeToJavaString.EncodeCesToChars("George's War in North America")); } }