C#用正则表达式 获取标签的属性或值

时间:2022-03-05 08:42:55

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

1、获取标签中的值: <a href="" >CSDN</a> 功效:CSDN

/// <summary> /// 获取字符中指定标签的值 /// </summary> /// <param>字符串</param> /// <param>标签</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="">CSDN</a>  获取 “href” 的功效:  

/// <summary> /// 获取字符中指定标签的值 /// </summary> /// <param>字符串</param> /// <param>标签</param> /// <param>属性名</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; }