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

    最近调试程序需要用到获取网页指定标签的属性和值,找到了一个比较好的正则匹配方法,特此备份。

    [原]C#用正则表达式 获取网页源代码标签的属性或值

    整理两个 在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;  
    }  

    举例说明

    string result = GetTitleContent(str, @"a"); //获取指定标签中的值
    string result = GetTitleContent(str, @"a",@"href"); //获取指定标签中的指定属性值
  • 相关阅读:
    MVC过滤器
    MVC自带的校验
    FPGA简单概述
    CAN总线扩展数据帧介绍
    简述人工智能发展的先决条件
    CAN总线标准帧
    CAN总线应用
    CAN总线优点
    CAN总线概述
    高速PCB设计注意事项
  • 原文地址:https://www.cnblogs.com/MobileBo/p/6582093.html
Copyright © 2011-2022 走看看