
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Returning the Entire Line in Which a Match Is Found
|
583
Console.WriteLine( );
lines = GetLines("Line1\r\nLine2\r\nLine3\nLine4", "Line", false);
foreach (string s in lines)
Console.WriteLine("MatchedLine: " + s);
}
Discussion
The GetLines method accepts three parameters:
source
The string or filename in which to search for a pattern
pattern
The regular expression pattern to apply to the source string
isFileName
Pass in true if the source is a filename or false if source is a string
This method returns a
List<string> of strings that contains each line in which the
regular expression match was found.
The
GetLines method can obtain the lines on which matches occur, within a string or
a file. When running a regular expression against a file with a name that is passed in
to the
source parameter (when isFileName equals true) in the GetLines method, the
file is opened and read line by line. The regular expression is run against each line
and, if a match is found, that line is stored in the
matchedLines List<string>. Using
the
ReadLine method of the StreamReader object saves you from having to determine
where each line starts and ends. Determining where a line starts and ends in a string
requires some work, as you shall see.
Running the regular expression against a string passed in to the
source parameter ...