2010-08-01 42 views
2

HI如何找到网站链接喜欢用正则表达式

我想要找到网站的链接喜欢这里的正则表达式选项:

www.yahoo.com 
yahoo.com 
http://www.yahoo.com 
http://yahoo.com 
yahoo.jp (or any domain) 
http://yahoo.fr 

反正是有跟踪它们全部用正则表达式?

回答

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

+0

我用那个,魔杖作品找到。 但有点问题, 我怎么找到返回的文本?我使用了 MatchCollection mc18 = Regex.Matches(text,regexOption,RegexOptions.IgnoreCase); 我应该怎么做才能找到文本? 关于 – pedram 2010-08-01 11:39:21

+0

您是要替换这些事件还是仅仅希望找到它们? – adamse 2010-08-01 11:42:15

+0

也是一个问题,我怎么能跟踪如果链接{} 像 {} www.yahooo.com或 {} www.yahooo.com 之间的问候 – pedram 2010-08-01 11:52:11

1

我要在这里扔出去的替代,都没有正则表达式的更多的细节。看看在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