///
/// 获取字符中指定标签的属性值
///
/// 字符串
/// 标签
/// 属性名
/// 属性
public static List GetTagAttr(string str, string tagName, string attrib)
{
string tmpStr = string.Format("]*?{1}=(['\"\"]?)(?[^'\"\"\\s>]+)\\1[^>]*>", tagName, attrib);
//获取
MatchCollection titleMatch = Regex.Matches(str, tmpStr, RegexOptions.IgnoreCase);
List list = new List();
foreach (Match m in titleMatch)
{
string result = m.Groups["url"].Value;
if (string.IsNullOrEmpty(result) || list.Contains(result)) continue;
list.Add(result);
}
return list;
}
///
/// 获取字符中指定标签的值
///
/// 字符串
/// 标签
/// 值
public static List GetTagContent(string str, string tagName)
{
string tmpStr = string.Format("<{0}[^>]*?>(?[^<]*){1}>", tagName, tagName); //获取
MatchCollection titleMatch = Regex.Matches(str, tmpStr, RegexOptions.IgnoreCase);
List list = new List();
foreach (Match m in titleMatch)
{
string result = m.Groups["Text"].Value;
if (string.IsNullOrEmpty(result) || list.Contains(result)) continue;
list.Add(result);
}
return list;
}
这段代码展示了如何使用正则表达式从HTML字符串中提取指定标签的属性值和内容。方法包括获取指定标签的属性值列表和标签内的文本内容,适用于网页解析和信息提取场景。
4万+

被折叠的 条评论
为什么被折叠?



