Named Groups

Here's a rewrite of the previous example, using a group that we name 'letter':


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {

      string regEx = 
        @"\b"                 +  // word boundary 
        @"(?'letter'\w)"      +  // match first letter, and name it 'letter' 
        @"\w+"                +  // match middle letters 
        @"\k'letter'"         +  // match last letter, denoted by 'letter' 
        @"\b";                   // word boundary 

     foreach (Match m in Regex.Matches ("bee cake level bob", regEx)) 
        Console.Write (m + " ");       
    }
}

The output:


level bob

To name a captured group:

 
(?'group-name'group-expr)  or  (?<group-name>group-expr)
  

To refer to a group:

 
\k'group-name'  or  \k<group-name>
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.