在 C# 中使用 match 提取两个字符串分隔符之间的字符串内容

本文关键字:字符串 两个 分隔符 之间 match 提取 | 更新日期: 2023-09-27 18:37:14

所以,假设我正在解析以下HTML字符串:

<html>
    <head>
        RANDOM JAVASCRIPT AND CSS AHHHHHH!!!!!!!!
    </head>
    <body>
        <table class="table">
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
            <tr><a href="/subdir/members/Name">Name</a></tr>
        </table>
    <body>
</html>

我想隔离**的内容(表类中的所有内容)

现在,我使用正则表达式来完成此操作:

string pagesource = (method that extracts the html source and stores it into a string);
string[] splitSource = Regex.Split(pagesource, "<table class=/"member/">;
string memberList = Regex.Split(splitSource[1], "</table>");
//the list of table members will be in memberList[0];
//method to extract links from the table
ExtractLinks(memberList[0]);

我一直在寻找其他方法来执行此提取,并且在 C# 中遇到了 Match 对象。

我正在尝试做这样的事情:

Match match = Regex.Match(pageSource, "<table class='"members'">(.|'n)*?</table>");

上面的目的是希望提取两个分隔符之间的匹配值,但是,当我尝试运行它时,匹配值为:

match.value = </table>

因此,我的问题是:有没有一种方法可以从我的字符串中提取数据,它比使用正则表达式的方法更容易/更具可读性/更短?对于这个简单的例子,正则表达式很好,但对于更复杂的例子,我发现自己的编码相当于整个屏幕上的涂鸦。

我真的很想使用 match,因为它看起来是一个非常整洁的类,但我似乎无法让它满足我的需求。谁能帮我解决这个问题?

谢谢!

在 C# 中使用 match 提取两个字符串分隔符之间的字符串内容

使用 HTML

解析器,如 HTML Agility Pack。

var doc = new HtmlDocument();
using (var wc = new WebClient())
using (var stream = wc.OpenRead(url))
{
    doc.Load(stream);
}
var table = doc.DocumentElement.Element("html").Element("body").Element("table");
string tableHtml = table.OuterHtml;

您可以将 XPath 与 HTmlAgilityPack 一起使用:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(s);
var elements = doc.DocumentNode.SelectNodes("//table[@class='table']");
foreach (var ele in elements)
{
    MessageBox.Show(ele.OuterHtml);
}

您在正则表达式中添加了括号以捕获匹配项:

Match match = Regex.Match(pageSource, "<table class='"members'">(.|'n*?)</table>") ;

无论如何,似乎只有查克·诺里斯才能使用正则表达式正确解析 HTML。