在以下函数(完美运行)中,我现在面临的挑战是让它不仅返回找到匹配项的位置,而且返回匹配项是什么......代码:
txtFilePattern 是一个管道分隔的文件扩展名列表。txtKeywords 是我正在寻找的关键字的多行文本框 txtPatterns 与 txtKeywords 相同,但适用于正则表达式模式。
这是我自己对 C# Grep 的小实验。
private List<Tuple<String, Int32, String>> ScanDocuments2()
{
Regex searchPattern = new Regex(@"$(?<=\.(" + txtFilePattern.Text + "))", RegexOptions.IgnoreCase);
string[] keywordtext = txtKeywords.Lines;
List<string> keywords = new List<string>();
List<Regex> patterns = new List<Regex>();
for (int i = 0; i < keywordtext.Length; i++)
{
if (keywordtext[i].Length > 0)
{
keywords.Add(keywordtext[i]);
}
}
string[] patterntext = txtPatterns.Lines;
for (int j = 0; j < patterntext.Length; j++)
{
if (patterntext[j].Length > 0)
{
patterns.Add(new Regex(patterntext[j]));
}
}
try
{
var files = Directory.EnumerateFiles(txtSelectedDirectory.Text, "*.*", SearchOption.AllDirectories).Where(f => searchPattern.IsMatch(f));
//fileCount = files.Count();
var lines = files.Aggregate(
new List<Tuple<String, Int32, String>>(),
(accumulator, file) =>
{
fileCount++;
using (var reader = new StreamReader(file))
{
var counter = 0;
String line;
while ((line = reader.ReadLine()) != null)
{
if (keywords.Any(keyword => line.ToLower().Contains(keyword.ToLower())) || patterns.Any(pattern => pattern.IsMatch(line)))
{
//cleans up the file path for grid
string tmpfile = file.Replace(txtSelectedDirectory.Text, "..");
accumulator.Add(Tuple.Create(tmpfile, counter, line));
}
counter++;
}
}
return accumulator;
},
accumulator => accumulator
);
return lines;
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
throw UAEx;
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
throw PathEx;
}
}
问题是 - 我如何确定通过哪个关键字或模式与我返回的元组匹配?