木子屋 Dnawo's BLOG

C#正则表达式之分组构造示例

👤 dnawo 📅 2009-09-14 👁 6767 👍 0 💬 0 🔄 来源:本站原创
我们常用的分组构造语法为:(子表达式),例如:

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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 设置Button、PictureBox、Label等控件背景透明 下一篇 → IE对CSS样式表的限制和解决方案