我目前正在構建一個 java 程序來自動化每周定期的體育課預訂,而不是手動預訂。為了實現這一點,我通過 http get 加載特定日期的類列表,并希望從響應中解析所需的類 id (foo/bar/ class-id )??s短的響應如下所示:<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,而不是“Weightlifting”這個詞之后的第一個。 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()); }
1 回答

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
好吧,你的正則表達式很貪婪,你需要讓它變得懶惰。
"Weightlifting.*?foo/bar/(.*?)\""
|
^ change this part
您可以使用的另一種模式是
(?<=data-url=")[^\/]+\/[^\/]+\/(\d+)
(?<=data-url\s*=\s*")
- 積極的回顧。檢查data-url=
[^\/]+\/[^\/]+\/
- 最多匹配兩個文本/
。(\d+)
- 匹配數字一次或多次(您要捕獲的 id)
添加回答
舉報
0/150
提交
取消