【发布时间】:2013-04-06 23:46:54
【问题描述】:
使用正则表达式,我希望能够获取多个 DIV 标记之间的文本。例如,以下内容:
<div>first html tag</div>
<div>another tag</div>
会输出:
first html tag
another tag
我使用的正则表达式模式只匹配我的最后一个 div 标签并且错过了第一个。 代码:
static void Main(string[] args)
{
string input = "<div>This is a test</div><div class=\"something\">This is ANOTHER test</div>";
string pattern = "(<div.*>)(.*)(<\\/div>)";
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine("Matches found: {0}", matches.Count);
if (matches.Count > 0)
foreach (Match m in matches)
Console.WriteLine("Inner DIV: {0}", m.Groups[2]);
Console.ReadLine();
}
输出:
找到的匹配项:1
内部 DIV:这是另一个测试
【问题讨论】:
-
这项任务是否必须使用正则表达式? HTML 是上下文无关文法,不能用正则表达式解析。很多时候你可以接近,但你最好使用 HTML 解析器。见stackoverflow.com/a/1732454/2022565