1

我有这样的 html 字符串(雅虎 xml 描述元素)

<img src="http://l.yimg.com/a/i/us/we/52/26.gif"/><br /> 
<b>Current Conditions:</b><br /> Cloudy, 1 C<BR /> <BR />
<b>Forecast:</b><BR /> Mon - Snow. High: -5 Low: -14<br /> Tue - Light Snow. High: -8 Low: -16<br /> <br /> 
....

我只想获得高值和低值(例如:-5、-14、-8、-16)

我尝试像这样使用 htmlAgilityPack:

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(rssDescriptionElement);
List<string> elements = new List<string>();

foreach (HtmlNode element in htmlDoc.DocumentNode.SelectNodes("//br"))
{
    elements.Add(element.NextSibling.InnerText);
}

elements上面 htmlString 的列表输出:

"\n"
"\nCloudy, 1 C"
"\n"
"Forecast:"
"\nMon - Snow. High: -5 Low: -14"
"\nTue - Light Snow. High: -8 Low: -16"
"\n"
"\n"
""
"\n(provided by "
"\n"

如何从此列表中仅获取高值和低值(-5、-14、-8、-16)或其他不同的解决方案?

4

1 回答 1

1

使用正则表达式:

(?:High|Low)\s*:\s*(?<num>-?\d+)

并获得名为num. 示例代码:

List<string> elements = new List<string>();
var pattern = @"(?:High|Low)\s*:\s*(?<num>-?\d+)";

foreach (HtmlNode element in htmlDoc.DocumentNode.SelectNodes("//br"))
{
    foreach(Match mc in Regex.Matches(element.NextSibling.InnerText, pattern))
    {
        elements.Add(mc.Groups["num"].ToString());
    }
}
于 2013-01-08T08:10:45.070 回答