如何从字符串解析网页链接?

时间:2014-07-04 11:41:13

标签: c# .net

Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    string rawString = link;
                    foreach (Match m in linkParser.Matches(rawString))
                    {
                        string links = m.Value;
                    }

我试图从这个字符串中解析/获取链接:

<a href="http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1"><b>

我想只获得这一部分:

http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1

但是我在字符串链接中的内容是:

http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1"><b

最后还剩下&#34;&gt;

2 个答案:

答案 0 :(得分:0)

尝试将\S+更改为[^\"\>]+

最终字符串:\b(?:https?:\/\/|www\.)[^\"\>]+\b

但这不仅仅是找到工作链接。如果您的链接类似于<a href="www.a<not working Link>flupp"><b>,则会找到www.a<not working Link

此表达式只查找下一个">之前的所有内容(如果它是有效的HTML表单,并且您知道两个引号之间的文本是普通链接,您只需要"(什么会让表达式成为\b(?:https?:\/\/|www\.)[^\"]+\b))。

使用它会找到www.a<not working Link>flupp,它正好位于两个引号之间。

如果您想禁止更多字符,则必须修改[^\"\>]+

顺便说一句:我认为在/

之后逃避?:https?:是有意义的

原因是因为你告诉他找到所有非空白字符,它应该以字母结尾。因为这个表达式是贪婪的,所以尽可能“吃掉”尽可能多的非空白字符。 ">不是空白字符,(TAB)。 [^\"]+告诉他获取所有字符,直到找到"。找到一个后他会停下来。

答案 1 :(得分:0)

我发现像某些人所说的那样使用HTMLAgilityPack,因为HTML不是常规语言。下载后,考虑到这是源中包含此文本的唯一节点:

            HtmlAgilityPack.HtmlDocument hp = new HtmlAgilityPack.HtmlDocument();
            string source = File.ReadAllText( @"C:\Users\Admin\Desktop\source.txt" );
            hp.LoadHtml(source);
            var node = hp.DocumentNode.SelectSingleNode("//a[contains(@href, 'http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1')]");
            string found = node.Attributes["href"].Value;                        
            Console.WriteLine(found);

您可以从任何地方获取源代码,可以通过webclient或本地文件下载。这将返回:http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112190&forum=scoops1