簡體   English   中英

正則表達式,用於讀取HTML中的標簽

[英]Regular expression to read tags in a HTML

<td width="100%"><h1>Chicago, IL Weather</h1></td>

我想在標簽h1中獲取文本。 為此,我想在C#中使用正則表達式代碼。 有人可以告訴我解決方案嗎?

    System.Text.RegularExpressions.Regex bodyRegex = new System.Text.RegularExpressions.Regex(@"(<h1[^>]*>[\u0000-\uFFFF]+?</h1>)");
System.Text.RegularExpressions.Match bodyMatch = bodyRegex.Match(line);
        if (bodyMatch.Success)
          {
           FileContent = bodyMatch.Result("$0");
           FileContent = (FileContent.Replace(@"<h1>", "")).Replace(@"</h1>", "");
}

通過此操作,您可以找到第一個h1標簽值

試一試

String h1Regex = "<h1[^>]*?>(?<TagText>.*?)</h1>";

MatchCollection mc = Regex.Matches(Data, h1Regex, RegexOptions.Singleline);

foreach (Match m in mc) {
    Console.Writeline (m.Groups["TagText"].Value);
}

為什么要使用Regex,我知道這是最快的方法,但是它也有缺點,例如:1.弄亂了代碼的可讀性,

  1. 如果您的html文件發生了更改,那么編寫新的正則表達式將非常痛苦,

除非您絕對需要,否則請離開regex並使用HTML解析器(如上述HTMLAgilityPack)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM