【发布时间】:2020-12-13 13:50:55
【问题描述】:
我正在开发一个可以读取和处理文本文件的应用程序。这些文本文件具有以下结构:
** A comment
* A command
Data, data, data
** Some other comment
* Another command
1, 2, 3
4, 5, 6
我使用string text = File.ReadAllText(file); 将整个文本文件存储在内存中。但是,我想删除所有作为注释的行,即所有以 "**" 开头的行。
这可以通过以下方法实现:
// this method also removes any white-spaces (this is intended)
string RemoveComments(string textWithComments)
{
string textWithoutComments = null;
string[] split = Regex.Split(text.Replace(" ", null), "\r\n|\r|\n").ToArray();
foreach (string line in split)
if (line.Length >= 2 && line[0] == '*' && line[1] == '*') continue;
else textWithoutComments += line + "\r\n";
return textWithoutComments;
}
然而,这对于大文件来说实际上是非常慢的。我还认为可以用一行代码(可能使用正则表达式)替换整个方法。我怎样才能做到这一点(我也从未使用过正则表达式)。
PS:我也想避开StreamReaders。
编辑
示例文件如下所示:
** Initial comment
*Command-0
** Some Comment: Header: Text
** Some text: text
*Command-1
**
** Some comment or text
**
*Command-2
*Command-3
1, 2, 3
2, 2, 4
3, 2, 5
** END COMMENT
【问题讨论】:
-
虽然它不会使解析本身更快,但您应该使用异步 IO。我也不清楚为什么你会使用
Regex而不是text.Split('\r', 'n'),而你的ToArray调用毫无意义,而且可能代价高昂。 -
文件有多大?
-
为什么要避免使用 StreamReader?如果您希望这更快,使用 StreamReader 处理文件就是您想要的。
-
@AluanHaddad 处理超过 100,000 行的文件,将
string[] split = Regex.Split(text.Replace(" ", null), "\r\n|\r|\n").ToArray();替换为string[] split = text.Replace(" ", null).Split('\r', '\n');执行时间从大约 100 毫秒到大约 60 毫秒。问题出在foreach循环中(执行需要几分钟)。 -
@Enigmativity 啊,我明白你的意思了,我正在考虑使用不同的文件 API。
标签: c# .net regex .net-framework-4.8