"&#,&#x,\u"开头的unicode介绍

转载地址:https://blog.csdn.net/u013243986/article/details/75287078

        最近在写爬虫时遇到"&#"或者 "&#x"开头的 编码,在浏览器是可以正常打开的,但是爬取下来时却,显示  中国农业银行 在尝试了  utf-8 或者GBK,GB2312等等的编码都行不通的情况下, 在网上也找不到太多的资料,这让我很苦恼,而且百度搜索居然没法直接搜索符号,还是大谷歌好用,  通过http://tool.chinaz.com/tools/unicode.aspx  发现其实这个只是普通的unicode编码.但是却有不同的格式 比如\u开头的,"&#"或者"&#x"开头.  我们在 https://www.zhihu.com/question/21390312   找到了 问题的答案.  

         其实  \u 开头和  &#x 开头是一样的  都是16进制 unicode字符的不同写法,&# 则是 unicode字符的10进制的写法.知道这个之后我们写代码就容易多了.

public static String unicode2String(String unicode)
{
    StringBuffer string = new StringBuffer();
    
    if (unicode.startsWith("&#x")) {
        String[] hex = unicode.replace("&#x", "").split(";");
        for (int i=0; i<hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            string.append((char) data);
        }
    } else if (unicode.startsWith("&#")) {
        String[] hex = unicode.replace("&#", "").split(";");
        for (int i=0; i<hex.length; i++) {
            int data = Integer.parseInt(hex[i], 10);
            string.append((char) data);
        }
    }

    return string.toString();
}

猜你喜欢

转载自blog.csdn.net/zhangge3663/article/details/84101832