Csharp/C#教程:正则表达式匹配拉href链接和字符串在 之间分享


正则表达式匹配拉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包含https://msdn.microsoft.com/en-us/library/Aa538627.aspx ; innerText (AKA 是标签之间的字符串 )包含ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ...

是不是比正则表达容易?

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

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

上述就是C#学习教程:正则表达式匹配拉href链接和字符串在 之间分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 using System.Collections.Generic; using System.Text.RegularExpressions; public struct LinkItem { public string Href; public string Text; public override string ToString() { return Href + "nt" + 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; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1007716.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐