Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Groups

Sometimes it’s useful to separate a regular expression into a series of subexpressions, or groups. For instance, consider the following regular expression that represents a U.S. phone number such as 206-465-1918:

\d{3}-\d{3}-\d{4}

Suppose we wish to separate this into two groups: area code and local number. We can achieve this by using parentheses to capture each group:

(\d{3})-(\d{3}-\d{4})

We then retrieve the groups programmatically as follows:

Match m = Regex.Match ("206-465-1918", @"(\d{3})-(\d{3}-\d{4})");

Console.WriteLine (m.Groups[1]);   // 206
Console.WriteLine (m.Groups[2]);   // 465-1918

The zeroth group represents the entire match. In other words, it has the same value as the match’s Value:

Console.WriteLine (m.Groups[0]);   // 206-465-1918
Console.WriteLine (m);             // 206-465-1918

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


 Â