java 获取页面的编码

今天遇到个问题,根据一个url获取页面,由于不知道页面的编码格式,需要自己在获得的页面中找到相应的charset,考虑使用正则表达式来获取,一下为获取编码的方法

1     /**
2      * 由于获取页面的原始编码
3      * @param htmlContent 页面的Content
4      */
5     public static String getChersetFromHtml(String htmlContent){
6         String regex="^([\\s\\S]*)(<meta\\s+http-equiv=\"Content-Type\"\\s+content=\"text/html;\\s*charset=)([-\\w+]+)(\"\\s*/?>[\\s\\S]*)$";
7         //获取第三个子表达式的内容
8         return htmlContent.replaceAll(regex, "$3");
9     }

这样就可以获得页面中的编码了。

参考资料:

http://edu.yesky.com/edupxpt/18/2143018.shtml  Java正则表达式详解
http://free-zhou.javaeye.com/blog/751417      html.replaceAll(regex, "$3"); 的活学活用
http://www.chinaunix.net/jh/26/154483.html    java 中正则的运用
http://www.jspcn.net/htmlnews/600100423.html   JAVA Pattern和Matcher 的用法
http://deerchao.net/tutorials/regex/regex.htm   (重要)正则
http://hi.baidu.com/gengshenspirit/blog/item/edb8a954df5825173a293592.html JAVA Pattern和Matcher 的用法

当然不使用正则表达式也可以获取,但是有点繁琐,不推荐。

原文地址:https://www.cnblogs.com/xiaozhihome/p/3071232.html