publicstaticvoid Main() { string s ="2005-2-21"; Regex reg =new Regex(@"(/d{4})-(/d{1,2})-(/d{1,2})",RegexOptions.Compiled); Match match = reg.Match(s); int year =int.Parse(match.Groups[1].Value); int month =int.Parse(match.Groups[2].Value); int day =int .Parse(match.Groups[3].Value); DateTime time =new DateTime(year,month,day); Console.WriteLine(time); Console.ReadLine(); }
从上例可以看出,第一个括号对包涵的组被自动编号为1,后面的括号依次编号为2、3……
publicstaticvoid Main() { string s ="2005-2-21"; Regex reg =new Regex(@"(?<2>/d{4})-(?<1>/d{1,2})-(?<3>/d{1,2})",RegexOptions.Compiled); Match match = reg.Match(s); int year =int.Parse(match.Groups[2].Value); int month =int.Parse(match.Groups[1].Value); int day =int .Parse(match.Groups[3].Value); DateTime time =new DateTime(year,month,day); Console.WriteLine(time); Console.ReadLine(); }
publicstaticvoid Main() { string s ="2005-2-21"; Regex reg =new Regex(@"(?<y>/d{4})-(?<m>/d{1,2})-(?<d>/d{1,2})",RegexOptions.Compiled); Match match = reg.Match(s); int year =int.Parse(match.Groups["y"].Value); int month =int.Parse(match.Groups["m"].Value); int day =int .Parse(match.Groups["d"].Value); DateTime time =new DateTime(year,month,day); Console.WriteLine(time); Console.ReadLine(); }