代码之家  ›  专栏  ›  技术社区  ›  monoceres

java中的Regex和ISO-8859-1字符集

  •  2
  • monoceres  · 技术社区  · 15 年前

    问题是我从matcher对象得到的字符串格式错误,像“”这样的加扰字符。

    如何阻止regex库扰乱我的角色?

    编辑:以下是一些代码:

    private HttpResponse sendGetRequest(String url) throws ClientProtocolException, IOException
    {
        HttpGet get = new HttpGet(url);
        return hclient.execute(get);
    }
    private static String getResponseBody(HttpResponse response) throws IllegalStateException, IOException
    {
        InputStream input = response.getEntity().getContent();
        StringBuilder builder = new StringBuilder();
        int read;
        byte[] tmp = new byte[1024];
    
        while ((read = input.read(tmp))!=-1)
        {
            builder.append(new String(tmp), 0,read-1);
        }
    
        return builder.toString();
    }
    HttpResponse response = sendGetRequest(url);
    String html = getResponseBody(response);
    Matcher matcher = forum_pattern.matcher(html);
    while(matcher.find()) // do stuff
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Alan Moore Chris Ballance    15 年前

    这可能是你问题的直接原因,而且 一定地 错误:

    builder.append(new String(tmp), 0, read-1);
    

    new String(byte[]) 构造函数不接受字符集,它使用平台默认编码。显然,平台上的默认编码不是ISO-8859-1。您应该能够从响应头中获取字符集名称,以便将其提供给构造函数。

    但无论如何,你不应该使用字符串构造函数;正确的方法是使用InputStreamReader。如果编码是像UTF-8这样的多字节编码之一,那么很容易损坏数据,因为一个字节块恰好在字符的中间结束。

    曾经 使用 新字符串(字节[]) 构造函数或 String.getBytes() 不接受字符集参数的方法。这些方法应该被弃用,并且在任何人使用它们时都应该发出强烈的警告。

        2
  •  2
  •   Community Mohan Dere    5 年前

    使用HTML解析器,这个问题和所有潜在的问题都将消失。

    我可以推荐你挑选 Jsoup

    另请参见: