使用正则表达式不是正确的做法。正如其他人指出的那样,使用HTML解析器。因为你接受它不会是一个完美的解决方案
99
但是,它可以用正则表达式来完成,只要:如果你有HTML Agility Pack,你可以这样做:
using System;
using System.Linq;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
string html = @"
Some text blah: page 13 of 99more stuff";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var nodes = doc.DocumentNode.SelectNodes("//td[@class='blah']");
if (nodes != null)
{
var td = nodes.FirstOrDefault();
if (td != null)
{
Match match = Regex.Match(td.InnerText, @"page \d+ of (\d+)");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}
}
}
输出。它是脆弱的,很容易被欺骗,但在这里它是:
class Program
{
static void Main(string[] args)
{
string s = @"stuff
Some text blah: page 13 of 99more stuff";
Match match = Regex.Match(s, @"
]*\sclass=""blah""[^>]*>[^");if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}
输出:
99
只要确保没有人见过你这样做。