繁体   English   中英

获取文件 C# 中字符串的行号

[英]get line number of string in file C#

该代码使用正则表达式对文件进行过滤,并调整结果。 但是如何获得文件中每个匹配项的行号? 我不知道该怎么做...请帮助我

class QueryWithRegEx  
enter code here


   
    IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);  

   
    System.Text.RegularExpressions.Regex searchTerm =  
        new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C\+\+|Studio)");  


    var queryMatchingFiles =  
        from file in fileList  
        where file.Extension == ".htm"  
        let fileText = System.IO.File.ReadAllText(file.FullName)  
        let matches = searchTerm.Matches(fileText)  
        where matches.Count > 0  
        select new  
        {  
            name = file.FullName,  
            matchedValues = from System.Text.RegularExpressions.Match match in matches  
                            select match.Value  
        };  


    Console.WriteLine("The term \"{0}\" was found in:", searchTerm.ToString());  

    foreach (var v in queryMatchingFiles)  
    {  
         
        string s = v.name.Substring(startFolder.Length - 1);  
        Console.WriteLine(s);  

      
        foreach (var v2 in v.matchedValues)  
        {  
            Console.WriteLine("  " + v2);  
        }  
    }  


    Console.WriteLine("Press any key to exit");  
    Console.ReadKey();  
}  

static IEnumerable<System.IO.FileInfo> GetFiles(string path)  
{  
    ...}

你可以从这个例子中理解:

从字符串中读取第 3 行

string line = File.ReadLines(FileName).Skip(14).Take(1).First();

从字符串中读取某个行号的文本

string GetLine(string text, int lineNo) 
{ 
  string[] lines = text.Replace("\r","").Split('\n'); 
  return lines.Length >= lineNo ? lines[lineNo-1] : null; 
}

给这个 go:

var queryMatchingFiles =
    from file in Directory.GetFiles(startFolder)
    let fi = new FileInfo(file)
    where fi.Extension == ".htm"
    from line in File.ReadLines(file).Select((text, index) => (text, index))
    let match = searchTerm.Match(line.text)
    where match.Success
    select new
    {
        name = file,
        line = line.text,
        number = line.index + 1
    };

从正则表达式匹配中检索行号可能很棘手,我将使用以下方法:

private static void FindMatches(string startFolder)
{
    var searchTerm = new Regex(@"Visual (Basic|C#|C\+\+|Studio)");

    foreach (var file in Directory.GetFiles(startFolder, "*.htm"))
    {
        using (var reader = new StreamReader(file))
        {
            int lineNumber = 1;
            string lineText;
            while ((lineText = reader.ReadLine()) != null)
            {
                foreach (var match in searchTerm.Matches(lineText).Cast<Match>())
                {
                    Console.WriteLine($"Match found: <{match.Value}> in file <{file}>, line <{lineNumber}>");
                }

                lineNumber++;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM