
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
584
|
Chapter 10: Regular Expressions
Note that if more than one match is found on a line, each matching line will be
added to the
List<string>.
See Also
See the “.NET Framework Regular Expressions,” “FileStream Class,” and “Stream-
Reader Class” topics in the MSDN documentation.
10.11 Finding a Particular Occurrence of a Match
Problem
You need to find a specific occurrence of a match within a string. For example, you
want to find the third occurrence of a word or the second occurrence of a social secu-
rity number. In addition, you may need to find every third occurrence of a word in a
string.
Solution
To find a particular occurrence of a match in a string, simply subscript the array
returned from
Regex.Matches:
public static Match FindOccurrenceOf(string source, string pattern,
int occurrence)
{
if (occurrence < 1)
{
throw (new ArgumentException("Cannot be less than 1",
"occurrence"));
}
// Make occurrence zero-based.
--occurrence;
// Run the regex once on the source string.
Regex RE = new Regex(pattern, RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(source);
if (occurrence >= theMatches.Count)
{
return (null);
}
else
{
return (theMatches[occurrence]);
}
}
To find each particular occurrence of a match in a string, build a List<Match> on the
fly: