
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Finding a Particular Occurrence of a Match
|
585
public static List<Match> FindEachOccurrenceOf(string source, string pattern,
int occurrence)
{
List<Match> occurrences = new List<Match>( );
// Run the regex once on the source string.
Regex RE = new Regex(pattern, RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(source);
for (int index = (occurrence - 1); index < theMatches.Count; index += occurrence)
{
occurrences.Add(theMatches[index]);
}
return (occurrences);
}
The following method shows how to invoke the two previous methods:
public static void TestOccurrencesOf( )
{
Match matchResult = FindOccurrenceOf
("one two three one two three one two three one"
+ " two three one two three one two three", "two", 2);
if (matchResult != null)
Console.WriteLine(matchResult.ToString( ) + "\t" + matchResult.Index);
Console.WriteLine( );
List<Match> results = FindEachOccurrenceOf
("one one two three one two three one "
+ " two three one two three", "one", 2);
foreach (Match m in results)
Console.WriteLine(m.ToString( ) + "\t" + m.Index);
}
Discussion
This recipe contains two similar but distinct methods. The first method,
FindOccurrenceOf, returns a particular occurrence of a regular expression match. The
occurrence you want to find is passed in to this method via the
occurrence ...