【问题标题】:java regular expressions regexjava正则表达式正则表达式
【发布时间】:2015-12-29 23:40:32
【问题描述】:

我在从网站提取数据时遇到问题。 我正在尝试获取公司名称并为其定价:SYGNITY8,40

<a class="link" href="http://www.money.pl/gielda/spolki-gpw/PLCMPLD00016.html">SYGNITY</a>

        </td>
        <td class="ac"><a href="javascript: OO('SGN','2015-10-01')"><img width="12" height="11" src="http://static1.money.pl/i/gielda/chart.gif" title="Pokaż wykres" alt="Pokaż wykres" /></a></td>
                        <td class="al">SGN</td>
                    <td class="ar">8,40</td> 

我尝试使用这种模式,但它不起作用:

String expr = "<a class=\"link\" href=\"(.+?)\">(.+?)</a>(.+?)<td class=\"ar\">(.+?)</td> ";

有什么建议吗?

【问题讨论】:

标签: java regex expression


【解决方案1】:

使用 JSoup 解析器

您应该使用像 JSoup 这样的 html 解析器,因为正则表达式不是解析 html 的好主意。

你可以这样做:

String htmlString = "YOUR HTML HERE";
Document document=Jsoup.parse(htmlString);
Element element=document.select("a[href=http://www.money.pl/gielda/spolki-gpw/PLCMPLD00016.html]").first();
System.out.println(element.text()); //SYGNITY

element=document.select("td[class=ar]").first();
System.out.println(element.text()); //8,40

使用正则表达式

如果您仍想使用正则表达式,那么您可以使用如下所示的正则表达式并从捕获组中获取内容:

PLCMPLD00016.html">(.*?)<\/a>|"ar">(.*?)<\/td> 

Working demo

String htmlString = "YOUR HTML HERE"
Pattern pattern = Pattern.compile("PLCMPLD00016.html">(.*?)<\\/a>|"ar">(.*?)<\\/td>");

Matcher matcher = pattern.matcher(htmlString );
while (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 2013-01-18
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多