2012-11-13 40 views
0

我到目前为止这一点:如何使用正则表达式提取标签链接(正则表达式 - C#)

<a href="(http://www.imdb.com/title/tt\d{7}/)".*?>.*?</a> 

C#

ArrayList imdbUrls = matchAll(@"<a href=""(http://www.imdb.com/title/tt\d{7}/)"".*?>.*?</a>", html); 
private ArrayList matchAll(string regex, string html, int i = 0) 
{ 
    ArrayList list = new ArrayList(); 
    foreach (Match m in new Regex(regex, RegexOptions.Multiline).Matches(html)) 
    list.Add(m.Groups[i].Value.Trim()); 
    return list; 
} 

我试图从一个HTML网页IMDB链接 这个正则表达式有什么问题?

这样做的主要思想是在谷歌搜索一部电影,然后找一个链接,IMDB的结果

+0

我不知道'C#'但内心'“”的想法'看起来很滑稽来给我捡回来...... – arkascha

+0

其双职高的C#它就像\“ –

+0

那么为什么封闭(外部)'''不能以同样的方式逃脱?这些是为了成为正则表达式分隔符? – arkascha

回答

1

正则表达式不是解析HTML文件的好选择.HTML不严格,也不是格式正规。

使用htmlagilitypack。您可以使用此代码使用HtmlAgilityPack

HtmlDocument doc = new HtmlDocument(); 
doc.Load(yourStream); 

List<string> anchorImdbList = doc.DocumentNode.SelectNodes("//a[@href]")//this xpath selects all anchor tags 
        .Select(p => p.Attributes["href"].Value) 
        .Where(x=>Regex.IsMatch(x,@".*?www\.imdb\.com.*?")) 
        .Select(y=>y) 
        .ToList<string>(); 
+0

它没有工作... 值不能为空。 参数名称:来源 我试图解析:http://www.google.com/search?q=imdb+The觉醒2011 Une –

+0

@AlexKapustian这可能是becuz一些锚标签可能没有'href'。 。编辑 – Anirudha

0

试试这个:

string tag = "tag of the link"; 
string emptystring = Regex.Replace(tag, "<.*?>", string.Empty); 

更新:

string emptystring = Regex.Replace(tag, @"<[^>]*>", string.Empty); 
+0

我认为这不起作用,因为我需要从页面中提取链接有很多这样的标签<> –

+0

@AlexKapustian查看更新 – aliboy38

0

您必须避开正斜杠。尝试:

<a href="(http:\/\/www.imdb.com\/title\/tt\d{7}\/)".*?>.*?<\/a> 

如果您需要从复杂页面中解析出html元素,则正则表达式会非常麻烦。像其他人所建议的那样尝试Html Agility Pack