【问题标题】:Jsoup matching with regexJsoup 与正则表达式匹配
【发布时间】:2013-09-08 09:35:20
【问题描述】:

我在使用 jsoup 时遇到了问题。我无法匹配 <div id="shout_132684"> 这些数字正在变化。我应该如何匹配这些?

Elements content = doc.select("div:matches(id=\"shout_.+?\")");

没用。

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    您可以使用 startswith CSS 选择器^=。 Jsoups.select(...)支持。

    你可以这样做:

    doc.select("div[id^=shout]");
    

    这是一个完整的例子:

    public static void main(String[] args)  {
        Document parse = Jsoup.parse("<div id=\"shout_23\"/>" +
                                     "<div id=\"shout_42\"/>" +
                                     "<div id=\"notValidId\"/>" +
                                     "<div id=\"shout_1337\"/>");
    
        Elements divs = parse.select("div[id^=shout");
    
        for (Element element : divs) {
            System.out.println(element);
        }
    }
    

    它将打印:

    <div id="shout_23"></div>
    <div id="shout_42"></div>
    <div id="shout_1337"></div>
    

    【讨论】:

      【解决方案2】:

      为了更准确的解析,您仍然可以使用正则表达式:

      Elements content = doc.select("div[id~=(shout_)[0-9]+]");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        相关资源
        最近更新 更多