【问题标题】:Jsoup getElementsByAttributeValueMatchingJsoup getElementsByAttributeValueMatching
【发布时间】:2017-09-04 14:51:55
【问题描述】:

[JSoup 讨论页面建议我在这里提问。]

所以,我不是正则表达式专家,但我想知道我从 jsoup 得到的结果 getElementsByAttributeValueMatching() 方法。

如果我的 html 页面包含(以及其他)以下链接:

<a href="/tweb/tiles/twr/EIDS_AT_20130108T134335/01/">Parent Directory</a>
<a href="1357681618315/">1357681618315/</a>
<a href="1357681649996/">1357681649996/</a>

我查询:

Elements dirs = baseDir.getElementsByAttributeValueMatching("href", Pattern.compile("[0-9]+/"));

希望只得到 2 个只有数字的链接(末尾有一个斜线)。

但是,我得到了所有 3 个链接。

我编写了一个快速测试程序来检查 java 的模式匹配器对带有 3 个 href 字符串的正则表达式的响应,并且它只返回两个只有数字的我所期望的:

String a = "/tweb/tiles/twr/EIDS_AT_20130108T134335/01/";
String b = "1357681618315/";
String c = "1357681649996/";

Pattern p = Pattern.compile("[0-9]+/");

System.out.println("a:"+ p.matcher(a).matches());
System.out.println("b:"+ p.matcher(b).matches());
System.out.println("c:"+ p.matcher(c).matches());

返回: 一个:假的 b:真 c:真

所以,我的问题是,我错过了什么?

谢谢, 莱纳斯

【问题讨论】:

    标签: java regex jsoup


    【解决方案1】:

    Jsoup 使用Matcher#find(),而不是Matcher#matches()。因此,您需要自己提供^$

    Elements dirs = baseDir.getElementsByAttributeValueMatching(
        "href", Pattern.compile("^[0-9]+/$"));
    

    这里是解释差异的相关 javadoc 摘录(强调我的)

    找到

    ...

    返回:

    true 当且仅当输入序列的一个 子序列 匹配此匹配器的模式

    匹配

    ...

    返回:

    true 当且仅当 整个 区域序列匹配此匹配器的模式

    至于为什么 Jsoup 使用find() 而不是matches(),这个问题你要问它的创建者。

    【讨论】:

    • 确实如此。我想也许文档可能会提到这一点。非常感谢!
    【解决方案2】:

    当我们在 jsoup 中使用 select 时,您可以使用 [attr*=valContaining][attr~=regex]

    元素 dirs = baseDir.select([attr~=regex]);

    attr----> 属性 正则表达式-----> 正则表达式应用于该属性的值

    请参阅此处的文档https://jsoup.org/apidocs/org/jsoup/select/Selector.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多