All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

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

Writer: aaa Article type: Programming skills(编程技巧) Time: 2013/12/6 10:24:51 Browse times: 368 Comment times: 0

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


Head photo

Go homepage
Upload pictures
Write articles

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

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

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






There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.