使用正則表達式,我想能夠獲得多個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 –