簡體   English   中英

使用正則表達式Java從html源提取文本

[英]Extract text from html source using regular expressions java

我喜歡使用正則表達式從html頁面提取文本。 這是我的代碼:

String regExp="<h3 class=\"field-content\"><a[^>]*>(\\w+)</a></h3>";
    Pattern regExpMatcher=Pattern.compile(regExp,Pattern.UNICODE_CHARACTER_CLASS);

    String example="<h3 class=\"field-content\"><a href=\"/humana-akcija-na-kavadarechkite-navivachi-lozari\">Проба 1</a></h3><h3 class=\"field-content\"><a href=\"/opshtina-berovo-ne-mozhe-da-sostavi-sovet-0\">Проба 2</a></h3>";
    Matcher m=regExpMatcher.matcher(example);
    while(m.find())
    {

        System.out.println(m.group(1));
    }

我喜歡獲取值Проба 1Проба 2 但是,我只得到第一個值Проба 1 我怎么了

使用正則表達式+ HTML是褻瀆行為。 但是,如果您真的想受到詛咒,那么這里就是(您已經警告過):


String regExp = "<h3 class=\"field-content\"><a[^>]*>([\\w\\s]+)</a></h3>";
                                                       ^updated part

由於Проба 1Проба 2還包含空格,因此您需要在模式中包含\\\\s

要發現黑暗面的力量,可以嘗試以下模式:

<h3 class=\"field-content\"><a[^>]*>([^<]+)</a></h3>

不要忘記之前設置UNICODE_CASE。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM