我目前正在构建一个Java程序,以使每周定期进行的体育课预订自动化,而不是手动进行预订。
为此,我通过http get加载了特定日期的类列表,并希望从响应中解析所需的类ID(foo / bar / class-id )。
缩短的响应如下:
<div>
<div class="row">
Olympic Weightlifting <br>
<a data-url="foo/bar/2099159">
Book
</a>
</div>
<div class="row">
Fitness <br>
<a data-url="foo/bar/2098939">
Book
</a>
</div>
</div>
到目前为止,以下代码段中的两个正则表达式是我能获得的最接近的正则表达式,但是它们都将匹配最后一个/第二个类ID,而不是“举重”一词之后的第一个。
String str = "<div>\n" +
"\t<div class=\"row\">\n" +
"\t\t\tOlympic Weightlifting <br>\n" +
"\n" +
"\t\t\t<a data-url=\"foo/bar/2099159\">\n" +
"\t\t\t\tBook\n" +
"\t\t\t</a>\n" +
"\t</div>\n" +
"\t<div class=\"row\">\n" +
"\t\t\tFitness <br>\n" +
"\n" +
"\t\t\t<a data-url=\"foo/bar/2098939\">\n" +
"\t\t\t\tBook\n" +
"\t\t\t</a>\n" +
"\t</div>\n" +
"</div>";
// regex 1: pattern multiline
Pattern p = Pattern.compile("Weightlifting.*foo/bar/(.*?)\"", Pattern.DOTALL);
// regex 2: inline multiline
// Pattern p = Pattern.compile("Weightlifting[\\s\\S]*foo/bar/(.*?)\"");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1).trim());
}
答案 0 :(得分:0)
您的正则表达式很贪婪,您需要使其变得懒惰。
"Weightlifting.*?foo/bar/(.*?)\""
|
^ change this part
您可以使用的另一种模式
(?<=data-url=")[^\/]+\/[^\/]+\/(\d+)
(?<=data-url\s*=\s*")
-令人反感。检查data-url=
[^\/]+\/[^\/]+\/
-将文本最多匹配两个/
。(\d+)
-一次或多次匹配数字(您要捕获的ID)