Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)aaa
published in(发表于) 2013/12/6 10:24:51
ASP.NET应用技巧:正则学习之组的定义及引用方式_.net资料_编程技术

ASP.NET应用技巧:正则学习之组的定义及引用方式_.net资料_编程技术-数科优化网

一个正则表达式匹配结果可以分成多个部分,这就是组(Group).
把一次Match结果用(?)的方式分成组,例子:
public static void 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["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();
}
也可以根据正则里面()的顺序,使用编码访问组.第一个括号对包涵的组被自动编号为1,后面的括号依次编号为2、3……
访问方式:match.Groups[1].Value


另外也可以用(?<数字>)的方式手工给每个括号对的组编号


苦闷的是如果过一段时间不使用正则的话,里面的符号很容易就忘记了,:-)






If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759