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;  
}  

 

注:以上方法為獲取字符串中第一個結果的值。可以使用Foreach讀取TitileMath中所有的匹配屬性或值。

http://blog.csdn.net/lhfly/article/details/7684319


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM