首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获取正则表达式匹配字符串的文件路径?

如何获取正则表达式匹配字符串的文件路径?
EN

Stack Overflow用户
提问于 2019-05-25 11:53:42
回答 2查看 464关注 0票数 1

我已经成功地使用"streamreader“从txt.files文件夹中匹配了多个字符串,但我还需要获取匹配字符串的文件路径。如何获取匹配字符串的文件路径?

代码语言:javascript
运行
复制
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");
                        }
                    }
                }
            }
        }

如果可能,我还希望输出字符串的文件路径。例如,

代码语言:javascript
运行
复制
C:/..../email_4.txt 
C:/..../email_7.txt
C:/..../email_8.txt
C:/..../email_9.txt
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-25 16:20:37

因为您已经有了DirectoryInfo,所以可以获得FullName属性。

您还有一个名为files的文件名。要获取文件的名称和位置,可以使用Path.Combine

更新后的代码可能如下所示:

代码语言:javascript
运行
复制
Console.WriteLine(count + "\t" + Path.Combine(di.FullName , Path.GetFileName(files)) + "\t" + match.Value + "\n");
票数 0
EN

Stack Overflow用户

发布于 2019-05-25 12:09:21

我猜我们可能只想匹配一些.txt文件。如果可能是这样,让我们从一个简单的表达式开始,它将收集从输入字符串的开头到.txt的所有内容,然后添加.txt作为右边界:

代码语言:javascript
运行
复制
^(.+?)(.txt)$

Demo

代码语言:javascript
运行
复制
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);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56301550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档