string str = "<img src=\"http://www.mzwu.com/01.gif\">图1</img><img src='http://www.mzwu.com/02.gif'>图2</img><img src=http://www.mzwu.com/03.gif>图3</img>";
string pattern = "<img[\\s\\S]*?src=(\"([^\"]*)\"|'([^']*)'|([^>\\s]*))[^>]*?>";
MatchCollection matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
textBox1.Text += match.Groups[2].Value + match.Groups[3].Value + match.Groups[4].Value + "\r\n";
}该语法捕获的子表达式存放在一个索引数组中,使用match.Groups[n].Value获取值,Groups[0].Value表示完整字符串,Groups[1].Value表示第1个括号内容,Groups[2].Value表示第2个括号内容,依此类推。
下边介绍另一种分组构造,语法为:(?<name>子表达式),它将捕获的子表达式存放在一个关联数组中,使用match.Groups[name].Value获取值,例如:
string str = "<img src=\"http://www.mzwu.com/01.gif\">图1</img><img src='http://www.mzwu.com/02.gif'>图2</img><img src=http://www.mzwu.com/03.gif>图3</img>";
string pattern = "<img[ \\s\\S]*?src=(\"(?<href>[^\"]*)\"|'(?<href>[^']*)'|(?<href>[^>\\s]*))[^>]*?>";
MatchCollection matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
textBox1.Text += match.Groups["href"].Value + "\r\n";
}
评论(0)
暂无评论。