December 2007
Intermediate to advanced
896 pages
19h 57m
English
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 matching substrings or only the matching substrings that are unique within the set of all matched strings.
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 = RE.Matches(source);
if (findAllUnique)
{
for (int counter = 0; counter < theMatches.Count; counter++)
{
if (!uniqueMatches.ContainsKey(theMatches[counter].Value))
{
uniqueMatches.Add(theMatches[counter].Value,
theMatches[counter]);
}
}
retArray = new Match[uniqueMatches.Count];
uniqueMatches.Values.CopyTo(retArray, 0);
}
else
{
retArray = new Match[theMatches.Count];
theMatches.CopyTo(retArray, 0);
}
return (retArray);
}The TestFindSubstrings method shown ...
Read now
Unlock full access