正则表达式匹配拉取 之间的字符串

本文关键字:之间 字符串 正则表达式 | 更新日期: 2023-09-27 17:55:45

可能的重复项:
正则表达式仅返回"链接"标签的"href"属性?

这是我的字符串,我想使用 C# 正则表达式从 href="pull this out" 中提取链接和标签之间的文本。不知道该怎么做。

<a href="http://msdn.microsoft.com/en-us/library/Aa538627.aspx" onclick="trackClick(this, '117', 'http'x3a'x2f'x2fmsdn.microsoft.com'x2fen-us'x2flibrary'x2fAa538627.aspx', '15');">ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ...</a>

正则表达式匹配拉取 <a></a> 之间的字符串

不要使用正则表达式来解析 HTML(如@hsz所述)。了解原因:正则表达式匹配开放标签,但 XHTML 自包含标签除外。取而代之的是,您可以使用像HtmlAgilityPack这样的HTML解析器:

var html = @"<a href=""http://msdn.microsoft.com/en-us/library/Aa538627.aspx"" onclick=""trackClick(this, '117', 'http'x3a'x2f'x2fmsdn.microsoft.com'x2fen-us'x2flibrary'x2fAa538627.aspx', '15');"">ToolStripItemOwnerCollectionUIAdapter.GetInsertingIndex Method ...</a>";
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(又名标签之间的字符串)包含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<LinkItem> Find(string file)
    {
    List<LinkItem> list = new List<LinkItem>();
    // 1.
    // Find all matches in file.
    MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
        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;
    }
}