
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
564
|
Chapter 10: Regular Expressions
To access each group, you must first use a loop to iterate each Match object in the
MatchCollection. For each Match object, you access the GroupCollection’s indexer,
using the following unnamed syntax:
string group1 = m.Groups[1].Value;
string group2 = m.Groups[2].Value;
or the following named syntax where m is the Match object:
string group1 = m.Groups["Group1_Name"].Value;
string group2 = m.Groups["Group2_Name"].Value;
If the Match method was used to return a single Match object instead of the
MatchCollection, use the following syntax to access each group:
// Unnamed syntax
string group1 = theMatch.Groups[1].Value;
string group2 = theMatch.Groups[2].Value;
// Named syntax
string group1 = theMatch.Groups["Group1_Name"].Value;
string group2 = theMatch.Groups["Group2_Name"].Value;
where theMatch is the Match object returned by the Match method.
See Also
See the “.NET Framework Regular Expressions” and “Hashtable Class” topics in the
MSDN documentation.
10.3 Verifying the Syntax of a Regular Expression
Problem
You have constructed a regular expression dynamically, either from your code or
based on user input. You need to test the validity of this regular expression’s syntax
before you actually use it.
Solution
Use the VerifyRegEx method shown in Example 10-4