我使用 Regex 和 Linq 在与模式匹配的文件夹中搜索所有 .txt 文件。这部分代码如下所示:
private static IEnumerable<string> Search(string file)
{
return File
.ReadLines(file)
.Select(line => Regex.Match(line, pattern))
.Where(match => match.Success)
.Select(match => match.Value)
.ToArray();
}
然后在 .txt 中写入匹配项:
var files = Directory.EnumerateFiles(filePath, "*.txt");
var extracts = files.SelectMany(file => Search(file));
File.WriteAllLines("results.txt", extracts);
无论如何要写出匹配来自的文件的名称吗?我有一个字符串数组中的文件名。
var filenames = Directory.GetFiles(filePath, "*.txt")
.Select(filename => Path.GetFileNameWithoutExtension(filename))
.Select(filename => Regex.Match(filename, namePattern))
.Where(match => match.Success)
.Select(match => match.Value)
.ToArray();
我的目标“results.txt”示例:
Example1 **file1.txt** Example2 **file2.txt** Example3 **file3.txt**
“示例”是已经在工作的部分,重点是我想以某种方式实现的。即使我必须重写整个代码,任何帮助也将不胜感激。谢谢!
您可以将文件名直接附加到匹配项:
var extracts = files.SelectMany(file => Search(file).Select(line => line + " " + file));
File.WriteAllLines("results.txt", extracts);
如果您需要在没有文件的情况下保持干净的“提取物”,您可以创建匿名对象:
var extracts = files.SelectMany(file => Search(file).Select(match => new {match, file}));
File.WriteAllLines("results.txt",
extracts.Select(extract => extract.match + " " + extract.file));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句