Illustrates the use of groups and captures : Group Capture « Regular Expressions « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Regular Expressions » Group CaptureScreenshots 
Illustrates the use of groups and captures
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);
        }

      }

    }

  }

}

           
       
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.