Capture Group of data objects
Description :
Capture objects having the same group of data
Name Spaces
using System;
using System.Text.RegularExpressions;
Code Segment
public class MyClass
{
public static void Main()
{
string text =
"(800) 555-1211\n" +
"(212) 555-1212\n" +
"(506) 555-1213\n" +
"(650) 555-1214\n" +
"(888) 555-1215\n";
string areaCodeRegExp = @"(?
string phoneRegExp = @"(?
MatchCollection myMatchCollection =
Regex.Matches(text, areaCodeRegExp + " " + phoneRegExp);
foreach (Match myMatch in myMatchCollection)
{
Console.WriteLine("Area code = " + myMatch.Groups["areaCodeGroup"]);
Console.WriteLine("Phone = " + myMatch.Groups["phoneGroup"]);
foreach (Group myGroup in myMatch.Groups)
{
foreach (Capture myCapture in myGroup.Captures)
{
Console.WriteLine("myCapture.Value = " + myCapture.Value);
}
}
}
}
}
Code Explanation
1. create a string containing area codes and phone numbers
2. 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"
3. 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"
4. create a MatchCollection object to store the matches
5. use a foreach loop to iterate over the Match objects in the MatchCollection object
6. display the "areaCodeGroup" group match directly
7. display the "phoneGroup" group match directly
8. use a foreach loop to iterate over the Group objects in myMatch.Group
9. use a foreach loop to iterate over the Capture objects in myGroup.Captures
By
Nathan