正则表达式匹配拉href链接和字符串在 之间

可能重复:
RegEx只返回’link’标签的’href’属性?

这是我的字符串,我想从href =“拉出来”和使用C#Regex的标签之间的文本中拉出链接。 不知道怎么做。

ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ... 

不要使用正则表达式来解析HTML(如@hsz提到的那样)。 了解原因: RegEx匹配除XHTML自包含标记之外的开放标记 。 而不是它你可以使用像HtmlAgilityPack这样的HTML解析器:

 var html = @"ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ..."; HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); var link = document.DocumentNode.SelectSingleNode("//a"); if (link != null) { var href = link.Attributes["href"].Value; var innerText = link.InnerText; } 

现在href包含http://msdn.microsoft.com/en-us/library/Aa538627.aspx ; innerText (AKA 是标签之间的字符串 )包含ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ...

是不是比正则表达容易?

这显示了如何做你想要的: C#刮HTML链接

以下是该页面的代码示例:

 using System.Collections.Generic; using System.Text.RegularExpressions; public struct LinkItem { public string Href; public string Text; public override string ToString() { return Href + "\n\t" + Text; } } static class LinkFinder { public static List Find(string file) { List list = new List(); // 1. // Find all matches in file. MatchCollection m1 = Regex.Matches(file, @"(.*?)", RegexOptions.Singleline); // 2. // Loop over each match. foreach (Match m in m1) { string value = m.Groups[1].Value; LinkItem i = new LinkItem(); // 3. // Get href attribute. Match m2 = Regex.Match(value, @"href=\""(.*?)\""", RegexOptions.Singleline); if (m2.Success) { i.Href = m2.Groups[1].Value; } // 4. // Remove inner tags from text. string t = Regex.Replace(value, @"\s*<.*?>\s*", "", RegexOptions.Singleline); i.Text = t; list.Add(i); } return list; } }