正则指引-括号(2)引用分组

static void Main(string[] args)
{
//引用分组
//使用括号之后,
//正则表达式会保存每个分组真正匹配的文本
//例如:
//表达式: (d{4})-(d{2})-(d{2})
//分组编号: 1 2 3
string str = "2013-12-12 2013-2-2";
string reg = @"(d{4})-(d{1,2})-(d{1,2})";
Match match = Regex.Match(str, reg);
while (match.Success)
{
foreach (Group g in match.Groups)
{
Console.WriteLine(g.Value);
}

Console.WriteLine(match.Value);

match = match.NextMatch();
}

//在替换中使用分组
string replaced = Regex.Replace(str, reg, "$1。。$2。。$3");//$+组号:获得对应组的匹配的内容
Console.WriteLine(replaced);

Console.ReadKey();
}

原文地址:https://www.cnblogs.com/lmfeng/p/3342727.html