Jsoup getElementsByAttributeValueMatching

use*_*162 4 java regex jsoup

[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>
Run Code Online (Sandbox Code Playgroud)

我查询:

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

希望只得到只有数字的2个链接(最后是一个斜线).

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

我编写了一个快速测试程序,用3 href字符串检查java的Pattern Matcher对该正则表达式的响应,并且它只返回两个只有我想要的数字:

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());
Run Code Online (Sandbox Code Playgroud)

返回:a:false b:true c:true

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

谢谢,Linus

Bal*_*usC 5

Jsoup使用Matcher#find(),而不是Matcher#matches().所以,你需要供应^$自己.

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

以下是解释差异的相关的javadoc摘录(强调我的):

...

返回:

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

火柴

...

返回:

trueif,且仅当整个区域序列与此匹配器的模式匹配时

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