標籤:style blog http color 使用 io ar for art
原文地址:http://blog.csdn.net/lhfly/article/details/7684319
整理兩個 在C#中,用Regex 擷取網頁原始碼標籤的屬性或值的方法 :
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中所有的匹配屬性或值。
C#用Regex 擷取網頁原始碼標籤的屬性或值