
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
558
|
Chapter 10: Regular Expressions
3. If you’ve called the Matches method to retrieve a MatchCollection object, iterate
over the
MatchCollection using a foreach loop. Each iteration will allow access to
every
Match object that the regular expression produced.
10.1 Enumerating Matches
Problem
You need to find one or more substrings corresponding to a particular pattern within
a string. You need to be able to inform the searching code to return either all match-
ing substrings or only the matching substrings that are unique within the set of all
matched strings.
Solution
Call the FindSubstrings method shown in Example 10-1, which executes a regular
expression and obtains all matching text. This method returns either all matching
results or only the unique matches; this behavior is controlled by the
findAllUnique
parameter. Note that if the findAllUnique parameter is set to true, the unique
matches are returned sorted alphabetically.
Example 10-1. FindSubstrings method
using System;
using System.Collections;
using System.Text.RegularExpressions;
public static Match[] FindSubstrings(string source, string matchPattern,
bool findAllUnique)
{
SortedList uniqueMatches = new SortedList( );
Match[] retArray = null;
Regex RE = new Regex(matchPattern, RegexOptions.Multiline);
MatchCollection theMatches ...