Then We put the regular expression logic into the StreamReader code to parse an entire file. We match each line.
Tip Groups is indexed starting at 1. Never access Groups, which can result in lots of grief as your algorithm does not work.
static void Main()
Regex regex = new Regex(@"\s/Content/([a-zA-Z0-9\-]+?)\.aspx");
// "\s/Content/" : space and then Content directory// "([a-zA-Z0-9\-]+?) : group of alphanumeric characters and hyphen// ? : don't be greedy, match lazily// \.aspx : file extension required for matchusing (StreamReader reader = new StreamReader(@"C:\programs\log.txt"))
while ((line = reader.ReadLine()) != null)
// Try to match each line against the Regex.
Match match = regex.Match(line);
// Write original line and the value.
string v = match.Groups.Value;
Console.WriteLine("... " + v);
}2008-10-16 23:56:44 W3SVC2915713 GET /Content/String.aspx - 80 66.249
2008-10-16 23:59:50 W3SVC2915713 GET /Content/Trim-String-Regex.aspx - 80 66.2492008-10-16 23:56:44 W3SVC2915713 GET /Content/String.aspx - 80 66.249
2008-10-16 23:59:50 W3SVC2915713 GET /Content/Trim-String-Regex.aspx - 80 66.249
Notes, file. Please create the log.txt file and place it somewhere and read it in with the above program. It is important to have the test file to see how the Regex code works.
Further usages. There are more usages of this kind of code in programs. We can match lines in files such as logs, trace files, scientific calculations, CSV files, or any text file.
Tip Processing each line separately may be faster because less memory must be accessed and fewer characters must be checked.
Detail We combined the StreamReader class with the Regex class in the base class library to parse large text files.
A summary. We used a regular expression on every line in a text file. We showed an accurate and simple way of matching every line in a text file.