Recently, due to work needs, I have learned some knowledge about regular expressions, mainly about how to use C # To search and match the desired information in log files (in TXT format, here, we will record some of the items we have written. I mainly want to match some information contained in the log:
Begin run:, 12:56:58
......
Passed tests: 7
Failed tests: 2
......
Ignored verifications: 0
Total execution time: 9 m 11 S
......
The specific method is as follows:
Public static void getinfo (string logpath, out string [] value) // logpath stores logs, value is output after obtaining the corresponding string
{< br> value = new string [5]; // I need to match the search strings with five
using (filestream FS = new filestream (path, filemode. open, fileaccess. read) // open the log file
{< br> using (streamreader sr = new streamreader (FS)
{< br> string [] linearray = sr. readtoend (). split (New String [] {"\ r \ n"}, stringsplitoptions. removeemptyentries); // stores the total number of lines of a log.
// Define RegEx to search info from. Log
RegEx rx1 = new RegEx (@".? (\ D {1, 2}/\ D {1, 2}/\ D {4}, \ D {1, 2 }:\ d {1, 2 }:\ d {1, 2} \ WM) ", regexoptions. ignorecase); // For Search matching begin run: 7/12/2011, 12:56:58 the time in the string, 12:56:58
RegEx rx2 = new RegEx (@ "passed tests: \ s + \ D {1, 3}", regexoptions. ignorecase); // search for numbers matching the passed tests: 7 string
RegEx rx3 = new RegEx (@ "failed tests: \ s + \ D {1, 3}", regexoptions. ignorecase); // search for numbers matching the failed tests: 2 string
RegEx rx4 = new RegEx (@ "ignored verifications: \ s + \ D {1, 3}", regexoptions. ignorecase); // to search for numbers matching the ignored verifications: 0 string
RegEx rx5 = new RegEx (@ "total execution time: \ s + \ D {1, 2} m + \ D {1, 2} s | total execution time: \ s + \ D {1, 2} m ", regexoptions. ignorecase); // In order to search for the time in the string that matches total execution time: 9 m 11s
Foreach (string line in linearray) // traverse row by row
{
If (rx1.match (Line). Success) // If a string that meets the rx1 condition is found
{
Val [0] = rx1.match (Line). value; // assign the string value to value
}
If (rx2.match (Line). Success)
{
Val [1] = rx2.match (Line). value. substring (17); // The index of 7 starting from the first letter P is 17 (including spaces)
}
If (rx3.match (Line). Success)
{
Val [2] = rx3.match (Line). value. substring (17 );
}
If (rx4.match (Line). Success)
{
Val [3] = rx4.match (Line). value. substring (23 );
}
If (rx5.match (Line). Success)
{
Val [4] = rx5.match (Line). value. substring (23 );
}
}
}
}
}
many articles only introduce common regular expressions, such as ZIP codes and telephones, so here I will record a specific example that I have encountered, how to perform full-text matching, search for strings, and pass values for your own learning and use.