我已经成功地使用"streamreader“从txt.files文件夹中匹配了多个字符串,但我还需要获取匹配字符串的文件路径。如何获取匹配字符串的文件路径?
static void abnormalitiescheck()
{
int count = 0;
Regex regex = new Regex(@"(@@@@@)");
DirectoryInfo di = new DirectoryInfo(txtpath);
Console.WriteLine("No" + "\t" + "Name and location of file" + "\t" + "||" +" " + "Abnormal Text Detected");
Console.WriteLine("=" + "\t" + "=========================" + "\t" + "||" + " " + "=======================");
foreach (string files in Directory.GetFiles(txtpath, "*.txt"))
{
using (StreamReader reader = new StreamReader(files))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Match match = regex.Match(line);
if (match.Success)
{
count++;
Console.WriteLine(count + "\t\t\t\t\t" + match.Value + "\n");
}
}
}
}
}
如果可能,我还希望输出字符串的文件路径。例如,
C:/..../email_4.txt
C:/..../email_7.txt
C:/..../email_8.txt
C:/..../email_9.txt
发布于 2019-05-25 16:20:37
因为您已经有了DirectoryInfo
,所以可以获得FullName属性。
您还有一个名为files
的文件名。要获取文件的名称和位置,可以使用Path.Combine
更新后的代码可能如下所示:
Console.WriteLine(count + "\t" + Path.Combine(di.FullName , Path.GetFileName(files)) + "\t" + match.Value + "\n");
发布于 2019-05-25 12:09:21
我猜我们可能只想匹配一些.txt
文件。如果可能是这样,让我们从一个简单的表达式开始,它将收集从输入字符串的开头到.txt
的所有内容,然后添加.txt
作为右边界:
^(.+?)(.txt)$
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"^(.+?)(.txt)$";
string input = @"C:/..../email_4.txt
C:/..../email_7.txt
C:/..../email_8.txt
C:/..../email_9.txt";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
https://stackoverflow.com/questions/56301550
复制相似问题