Java中的正则表达式,无法搜索所有HTML

时间:2013-01-27 23:17:55

标签: java regex

我在Android平台上使用Java正则表达式。

我正在尝试搜索this HTML以定义正则表达式。

这是我的代码:

    public void mainaaForWWW(String websiteSource){

    try {
        websiteSource = readDataFromWWW(websiteSource);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    ArrayList<String> cinemaArray = new ArrayList<String>();
    Pattern sample = Pattern.compile("<div class=\"theatre\">");
    Matcher secuence = sample.matcher(websiteSource);
    try {
        while (secuence.find()) {
            cinemaArray.add(secuence.group());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    titleTableForWWW = new String[cinemaArray.size()];
    for(int i = 0; i < titleTableForWWW.length; i++)
        titleTableForWWW[i] = cinemaArray.get(i);
}

问题很奇怪,因为当我调试代码时,String websiteSource没问题(所有HTML文件都已完全加载),但只有4个while循环。在HTML文档中,我手动找到了11个匹配项。简化此正则表达式只是为了找到正在发生的事情。有什么想法吗?

好的,我的坏。我找到了解决方案:

所以,这是我的代码,负责将HTML源代码写入String

public String readDataFromWWW(String UrlAdress) throws IOException
    {

        String line = null;
        URL url = new URL(UrlAdress);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
        while (rd.readLine() != null) {
            line += rd.readLine();
        }

        System.out.println(line);

        return line;

我认为读取字符串的方式,可能会搞砸了,所以我用这个替换了这个方法:

public String readDataFromWWW(String UrlAdress) throws IOException
    {
        String wyraz = "";

         try {
                String webPage = UrlAdress;
                URL url = new URL(webPage);
                URLConnection urlConnection = url.openConnection();
                InputStream is = urlConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "ISO-8859-2");

                int numCharsRead;
                char[] charArray = new char[1024];
                StringBuffer sb = new StringBuffer();
                while ((numCharsRead = isr.read(charArray)) > 0) {
                    sb.append(charArray, 0, numCharsRead);
                }
                wyraz = sb.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        return wyraz;
    }

一切都很好!非常感谢您的线索和帮助。我认为这个问题与撰写String期间的换行有关,但我不太确定。

0 个答案:

没有答案