簡體   English   中英

使用正則表達式匹配字符串中的多個URL

[英]Matching several URLs in a string using regex

我試圖從此處使用正則表達式來匹配字符串中的URL: 正則表達式以匹配Java中的URL

它對一個URL可以正常工作,但是當我在字符串中有兩個URL時,它僅與后者匹配。

這是代碼:

Pattern pat = Pattern.compile(".*((https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])", Pattern.DOTALL);
Matcher matcher = pat.matcher("asdasd http://www.asd.as/asd/123 or http://qwe.qw/qwe");
// now matcher.groupCount() == 2, not 4

編輯:我嘗試過的東西:

// .* removed, now doesn't match anything // Another edit: actually works, see below
Pattern pat = Pattern.compile("((https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])", Pattern.DOTALL);

// .* made lazy, still only matches one
Pattern pat = Pattern.compile(".*?((https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])", Pattern.DOTALL);

有任何想法嗎?

這是因為.*是貪婪的。 它只會消耗盡可能多的(整個字符串),然后回溯。 也就是說,它將一次丟棄一個字符,直到其余字符組成一個URL。 因此,第一個URL將已經被匹配,但是沒有被捕獲。 不幸的是,比賽不能重疊。 修復應該很簡單。 刪除模式開頭的.* 然后,您還可以從模式中刪除外部括號-不再需要捕獲任何內容,因為整個匹配項都是您要查找的URL。

Pattern pat = Pattern.compile("(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]", Pattern.DOTALL);
Matcher matcher = pat.matcher("asdasd http://www.asd.as/asd/123 or http://qwe.qw/qwe");
while (matcher.find()) {
  System.out.println(matcher.group());
}

順便說一句, matcher.groupCount()不會告訴您任何信息,因為它給您的是模式中的組數,而不是目標字符串中的捕獲數。 這就是為什么您的第二種方法(使用.*? )沒有幫助的原因。 模式中仍然有兩個捕獲組。 在調用find或任何東西之前, matcher不知道它將總共找到多少個捕獲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM