zoukankan      html  css  js  c++  java
  • C#用正则表达式 获取网页源代码标签的属性或值

     原文地址:http://blog.csdn.net/lhfly/article/details/7684319

    整理两个 在C#中,用正则表达式 获取网页源代码标签的属性或值的方法 :

    1、获取标签中的值: <a href="www.csdn.net" class="main" >CSDN</a> 结果:CSDN

            /// <summary>
            /// 获取字符中指定标签的值
            /// </summary>
            /// <param name="str">字符串</param>
            /// <param name="title">标签</param>
            /// <returns></returns>
            public static string GetTitleContent(string str, string title)
            {
                string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", title, title); //获取<title>之间内容
    
                Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
    
                string result = TitleMatch.Groups["Text"].Value;
                return result;
            }

    2、获取标签中的属性: <a href="www.csdn.net" class="main">CSDN</a>  获取 “href” 的结果:www.csdn.net

            /// <summary>
            /// 获取字符中指定标签的值
            /// </summary>
            /// <param name="str">字符串</param>
            /// <param name="title">标签</param>
            /// <param name="attrib">属性名</param>
            /// <returns>属性</returns>
            public static string GetTitleContent(string str, string title,string attrib)
            {
    
                string tmpStr = string.Format("<{0}[^>]*?{1}=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>", title, attrib); //获取<title>之间内容
    
                Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
    
                string result = TitleMatch.Groups["url"].Value;
                return result;
            }

    注:以上方法为获取字符串中第一个结果的值。可以使用Foreach读取TitileMath中所有的匹配属性或值。

  • 相关阅读:
    HDU
    HDU
    HDU
    2016蓝桥杯省赛C/C++A组第二题 跳蚱蜢
    2016蓝桥杯决赛C/C++A组第四题 路径之谜
    【洛谷P2397】yyy loves Maths VI (mode)【模拟】
    【洛谷P2397】yyy loves Maths VI (mode)【模拟】
    【NOIP2018】【洛谷P5017】摆渡车【DP】
    【NOIP2018】【洛谷P5017】摆渡车【DP】
    2018NOIP普及组 划水记
  • 原文地址:https://www.cnblogs.com/chenghu/p/3941261.html
Copyright © 2011-2022 走看看