专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

怎样在C#中用正则表达式取出标签中内的内容

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:14:38       共计:3628 浏览



C#中使用正则表达式取出标签中内的内容的方法如下:

      /// <summary>  

       /// 获取字符中指定标签的值  

       /// </summary>  

       /// <param name="str"> 字符串 </param>  

       /// <param name="tagName"> 标签 </param>  

       /// <param name="attrib"> 属性名 </param>  

       /// <returns> 属性 </returns>  

       public static List<string> GetTagAttr(string str, string tagName, string attrib)

       {

           string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", tagName, attrib);

           // 获取 <Script> 属性值  


           MatchCollection titleMatch = Regex.Matches(str, tmpStr, RegexOptions.IgnoreCase);


           List<string> list = new List<string>();

           foreach (Match m in titleMatch)

           {

               string result = m.Groups["url"].Value;

               if (string.IsNullOrEmpty(result) || list.Contains(result)) continue;


               list.Add(result);

           }


           return list;

       }


       /// <summary>  

       /// 获取字符中指定标签的值  

       /// </summary>  

       /// <param name="str"> 字符串 </param>  

       /// <param name="tagName"> 标签 </param>  

       /// <returns> 值 </returns>  

       public static List<string> GetTagContent(string str, string tagName)

       {

           string tmpStr = string.Format ("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", tagName, tagName); // 获取 < Script > 之间内容  


           MatchCollection titleMatch = Regex.Matches(str, tmpStr, RegexOptions.IgnoreCase);


           List<string> list = new List<string>();

           foreach (Match m in titleMatch)

           {

               string result = m.Groups["Text"].Value;

               if (string.IsNullOrEmpty(result) || list.Contains(result)) continue;


               list.Add(result);

           }

           return list;

       }


版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:nginx怎么实现http跳转到https | ·下一条:在C#中正则表达式校验IP格式写法

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有