嗨即時查找字符串中的URL,我使用正則表達式創建了許多關於此問題的主題,但我遇到了問題。使用此模式:在字符串中查找URL
String regex = "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" +
"(\\w+:\\[email protected])?(([-\\w]+\\.)+(com|org|net|gov" +
"|mil|biz|info|mobi|name|aero|jobs|museum" +
"|travel|[a-z]{2}))(:[\\d]{1,5})?" +
"(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" +
"((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" +
"(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" +
"(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b";
它的作品在大多數頁面中都很好,但我遇到了其他問題。例如:
回報
的問題是空間。
任何人都有一個很好的模式,解決這個問題?
謝謝。
編輯::這是我的代碼
private ArrayList<String> pullLinks(String text) {
ArrayList<String> links = new ArrayList<String>();
String regex = "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)" +
"(\\w+:\\[email protected])?(([-\\w]+\\.)+(com|org|net|gov" +
"|mil|biz|info|mobi|name|aero|jobs|museum" +
"|travel|[a-z]{2}))(:[\\d]{1,5})?" +
"(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" +
"((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" +
"(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" +
"([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" +
"(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
{
urlStr = urlStr.substring(1, urlStr.length() - 1);
}
links.add(urlStr);
}
return links;
}
Offtopic:還有更多的頂級頂級域名(TLD)多於2個字母,即您列出的頂級域名。查看[Wikipedia的TLD列表](http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains)。你的正則表達式也會丟失這樣寫的URL:'example.com'。 – 2012-03-16 13:10:46
Offtopic,但這裏有一個很好的匹配網址的模式,按行解釋:http://daringfireball.net/2010/07/improved_regex_for_matching_urls – Holm 2012-03-16 13:18:14