首页 > 解决方案 > C#将字符串列表保存到文件中,每个条目之间用空行保存

问题描述

在 .NET Core 3.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.

标签: c#

解决方案


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

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

(Entry\t.*)\n

或者

(Entry\t.*)\r\n

然后,在 foreach 循环中,使用

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

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


推荐阅读