Mega Code Archive

 
Categories / C# Book / 11 Regular Expression Basics
 

0656 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>