Csharp/C Sharp/Regular Expressions/Group Capture — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:47, 26 мая 2010

Illustrates the use of groups and captures

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  ExampleC_2.cs illustrates the use of groups and captures
*/
using System;
using System.Text.RegularExpressions;
public class ExampleC_2
{
  public static void Main()
  {
    // create a string containing area codes and phone numbers
    string text =
      "(800) 555-1211\n" +
      "(212) 555-1212\n" +
      "(506) 555-1213\n" +
      "(650) 555-1214\n" +
      "(888) 555-1215\n";
    // create a string containing a regular expression to
    // match an area code; this is a group of three numbers within
    // parentheses, e.g. (800)
    // this group is named "areaCodeGroup"
    string areaCodeRegExp = @"(?<areaCodeGroup>\(\d\d\d\))";
    // create a string containing a regular expression to
    // match a phone number; this is a group of seven numbers
    // with a hyphen after the first three numbers, e.g. 555-1212
    // this group is named "phoneGroup"
    string phoneRegExp = @"(?<phoneGroup>\d\d\d\-\d\d\d\d)";
    // create a MatchCollection object to store the matches
    MatchCollection myMatchCollection =
      Regex.Matches(text, areaCodeRegExp + " " + phoneRegExp);
    // use a foreach loop to iterate over the Match objects in
    // the MatchCollection object
    foreach (Match myMatch in myMatchCollection)
    {
      // display the "areaCodeGroup" group match directly
      Console.WriteLine("Area code = " + myMatch.Groups["areaCodeGroup"]);
      // display the "phoneGroup" group match directly
      Console.WriteLine("Phone = " + myMatch.Groups["phoneGroup"]);
      // use a foreach loop to iterate over the Group objects in
      // myMatch.Group
      foreach (Group myGroup in myMatch.Groups)
      {
        // use a foreach loop to iterate over the Capture objects in
        // myGroup.Captures
        foreach (Capture myCapture in myGroup.Captures)
        {
          Console.WriteLine("myCapture.Value = " + myCapture.Value);
        }
      }
    }
  }
}