正則指引-括號(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();
}引用

相關文章
相關標籤/搜索