zoukankan      html  css  js  c++  java
  • 用正则获取网页中的标签内容

         有个同事想要从html网页标签中提取特定内容,让我帮忙看看。我研究了下,做了个小工具。

        目标:匹配出  <p><label id="catalog_FUND">基金:</label> 这个p标签里面的a标签的内容

        解决方案:由于一次性匹配出来,难度太大,因此可分为两步走,首先获取这个p标签里面的所有a标签,如下图所示:

         

    然后,再从这些a标签中获取内容,如图:

    正则:

    <p><label id="catalog_FUND">基金:</label>((<a[^><]*>([^><]*)</a>)*?)</p>
    <a[^><]*>([^><]*)</a>

    由上面正则可以看出,用的最多的就是[^><]*不包括尖括号的任意多个字符,?表示非贪婪模式,表示在满足匹配的情况下,尽可能少的匹配a标签。

     附小工具的后台代码:

     1  private void Readtxt_Click(object sender, RoutedEventArgs e)
     2         {
     3             //从当前目录获取文件
     4 
     5             string dir = Environment.CurrentDirectory;
     6 
     7             string path = dir + @"Content.txt";
     8 
     9             if (File.Exists(path))
    10             {
    11                 var content = File.ReadAllText(path, Encoding.Default);
    12 
    13                 this.orginText.AppendText(content);
    14             }
    15         }
    16 
    17         private void testMatch_Click(object sender, RoutedEventArgs e)
    18         {
    19             TextRange textRange = new TextRange(orginText.Document.ContentStart, orginText.Document.ContentEnd);
    20             var content = textRange.Text;
    21             var pattern = regular.Text;
    22 
    23             if (pattern != "" && content != "")
    24             {
    25                 if (Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
    26                 {
    27                     MessageBox.Show("ok");
    28                     var maches = Regex.Matches(content, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
    29                     if (maches.Count > 0)
    30                     {
    31                         foreach (Match item in maches)
    32                         {
    33                             if (item.Success)
    34                             {
    35                                 if (item.Groups.Count > 0)
    36                                 {
    37                                     ResultText.AppendText(item.Groups[1].Value);
    38                                 }
    39                             }
    40                         }
    41                     }
    42                 }
    43                 else
    44                 {
    45                     MessageBox.Show("fail");
    46                 }
    47             }
    48         }
  • 相关阅读:
    第36课 经典问题解析三
    第35课 函数对象分析
    67. Add Binary
    66. Plus One
    58. Length of Last Word
    53. Maximum Subarray
    38. Count and Say
    35. Search Insert Position
    28. Implement strStr()
    27. Remove Element
  • 原文地址:https://www.cnblogs.com/wangqiang3311/p/7741601.html
Copyright © 2011-2022 走看看