c# - 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.
解决方案
您的正则表达式捕获整行,包括尾随的“\n”(或“\r\n”)。
根据确切的文件格式,您应该将您的正则表达式更改为:
(Entry\t.*)\n
或者
(Entry\t.*)\r\n
然后,在 foreach 循环中,使用
result.Add(m.Groups[1].Value);
这只会添加第一个捕获组,即“()”中的内容,跳过换行符。
推荐阅读
- angular - Material-UI 下拉菜单在更新到 Angular 8 后导致 IE11 中的错误
- java - 使用java解析SQL语句并修改后重构
- node.js - 如何修复以下创建节点 js 类的错误?
- git - git filter-branch 错误:“致命:不是有效的对象名称 HEAD”
- sql-server - 在计算字段中使用聚合函数
- python - 如何最小化 x 轴上的日期时间刻度数
- mysql - 在同一张表中使用外键
- ios - 每个请求都有不同的 json 对象
- python - 更改固定关键字的 django haystack 搜索结果准确性
- excel - 公开 Excel InlineShapes 以进行编辑