HI
我想要正则表达式选项,找到像这里的网站链接:
www.yahoo.com
yahoo.com
http://www.yahoo.com
http://yahoo.com
yahoo.jp ( or any domain)
http://yahoo.fr
无论如何都要用正则表达式来跟踪它们吗?
答案 0 :(得分:1)
我要在这里抛出一个替代方案,而不是RegEx。看一下HTML Agility Pack,你的情况会是这样的:
var doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[contains(@href, 'yahoo')]"])
{
var href = link["href"];
//href is a url that contains the word `yahoo`, do something with it
}
正如你所写的那样,回答这个问题并非如此,只是让你的选项保持开放状态,如RegEx can have many other problems when applied against HTML。
答案 1 :(得分:0)
来自daringfireball.net的这个正则表达式应该能够做你想要的最多。我不确定domain.tld
,因为这是非常含糊的。
(?xi)
\b
( # Capture 1: entire matched URL
(?:
[a-z][\w-]+: # URL protocol and colon
(?:
/{1,3} # 1-3 slashes
| # or
[a-z0-9%] # Single letter or digit or '%'
# (Trying not to match e.g. "URI::Escape")
)
| # or
www\d{0,3}[.] # "www.", "www1.", "www2." … "www999."
| # or
[a-z0-9.\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash
)
(?: # One or more:
[^\s()<>]+ # Run of non-space, non-()<>
| # or
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
)+
(?: # End with:
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
| # or
[^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
)
)
有关其功能的详细信息,请查看http://daringfireball.net/2010/07/improved_regex_for_matching_urls