I want to loop through the lines on a file, and match as regular expression of ID’d to each line.
Then when there is a match I want to print the line number followed by the actual match.
So:
string folderToSearch = @"C:\Projects\Unilever\Database";
string idsToMacthAsRegexp = "1943|3937";
DirectoryInfo dir = new DirectoryInfo(folderToSearch);
FileInfo[] filesToSearch = dir.GetFiles("*.sql", SearchOption.AllDirectories);
foreach (FileInfo f in filesToSearch)
{
string line;
using (StreamReader reader = new StreamReader(f.FullName))
{
while ((line = reader.ReadLine()) != null)
{
if (Regex.IsMatch(line, idsToMacthAsRegexp))
{
// I want to print the portion that matches but cant
// even remember what this is called, or how to do it!
}
}
}
}
Console.ReadLine();
Use the
Regex.Matchmethod instead ofRegex.IsMatch. That will return aMatchobject which lets you check theSuccessproperty, then refer to the matched value:As for the line numbers, that has nothing to do with the regex (unless that is something you’re matching, but that doesn’t seem to be the case from your pattern). For that perhaps you want to declare a counter variable outside of your loop, set to zero, and increment it on every pass of the loop (right after the
whilestatement).