正则学习:组的定义及引用方式

来源:互联网 发布:cs架构b2b源码 编辑:程序博客网 时间:2024/06/06 01:40
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
一个正则表达式匹配结果可以分成多个部分,这就是组(Group).
把一次Match结果用(?<name>)的方式分成组,例子:
public static void 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();
}
也可以根据正则里面()的顺序,使用编码访问组.第一个括号对包涵的组被自动编号为1,后面的括号依次编号为2、3……
访问方式:match.Groups[1].Value

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

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

http://www.cnblogs.com/waitu/archive/2006/08/31/491192.html

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击