代码之家  ›  专栏  ›  技术社区  ›  Stpete111

C#将字符串列表保存到文件中,在每个条目之间用空行保存

c#
  •  0
  • Stpete111  · 技术社区  · 5 年前

    在.NETCore3.1中编写控制台应用程序。在下面,我将从一个匹配集合中获取所有正则表达式匹配,并将它们写入一个文本文件,每个文本文件都有自己的行。请注意 modifiedFiles <FileInfo> .

    using System.IO;
    using System.Configuration;
    using System.Text;
    using System.Text.RegularExpressions;
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    namespace LogFiles
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string sourcePath = ConfigurationManager.AppSettings["sourcepath"];
                string targetPath = ConfigurationManager.AppSettings["destpath"];
                Regex rx1 = new Regex(@"(Entry\t.*)",
                RegexOptions.Compiled | RegexOptions.IgnoreCase);
    
    
                var modifiedFiles = ModifiedFileFinder.GetFilesModifiedInLast24Hours(sourcePath);
    
                    foreach (var file in modifiedFiles)
                    {
                    var fileContent = File.ReadAllText(file.ToString());
                    var fileName = file.Name;
                    var newFile = String.Concat(targetPath, fileName);
                    MatchCollection matches = rx1.Matches(fileContent);
    
                    if (matches.Count > 0)
                        {
                        var result = new List<string>();
    
                        foreach (Match m in matches)
                        {
                            result.Add(m.Value);
                        }
                        File.WriteAllLines(newFile, result);
                        }
                    }  
               }              
           }
       }
    

    结果文件中的文本如下所示:

    Entry  this is item 1.
     
    Entry  this is item 2.
     
    Entry  this is item 3.
    

    Entry  this is item 1.
    Entry  this is item 2.
    Entry  this is item 3.
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Disti    5 年前

    正则表达式捕获整行,包括尾随的“\n”(或“\r\n”)。

    根据确切的文件格式,您应该将正则表达式更改为:

    (Entry\t.*)\n
    

    (Entry\t.*)\r\n
    

    result.Add(m.Groups[1].Value);
    

    这只添加第一个捕获组,即“()”中的内容,跳过换行符。

        2
  •  1
  •   Johnathan Barclay    5 年前

    阅读 docs . 匹配换行符( \n )因此,这不是在输出文件中有额外行的原因。

    . 通配符:匹配除\n以外的任何单个字符。

    但是,它与回车符匹配( \r

    空行在输出文件中是否可见完全取决于您使用的文本编辑软件,以及它如何解释独立文本 \r

    避免这种情况的最可靠的方法是匹配除 \r :

    (Entry\t[^\n\r]*)