使用正则表达式,我想能够获得多个DIV标签之间的文本。例如,以下内容:使用正则表达式来获取多个HTML标签之间的文本
<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解析器会更好。请参阅http://stackoverflow.com/a/1732454/2022565 –