正则指引-括号(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);string

match = match.NextMatch();
}it

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

Console.ReadKey();
}引用

相关文章
相关标签/搜索