【发布时间】:2013-08-23 22:43:22
【问题描述】:
我正在寻找有关 RegEx 模式的一些指导。
我有一个管道分隔文件,我想删除所有第四个单元格为空白的行。每行可以有任意数量的单元格。
到目前为止我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace EpicRemoveBlankPriceRecords
{
class Program
{
static void Main(string[] args)
{
string line;
// Read the file and display it line by line.
System.IO.StreamReader inFile = new System.IO.StreamReader("c:\\test\\test.txt");
System.IO.StreamWriter outFile = new System.IO.StreamWriter("c:\\test\\test_out.txt");
while ((line = inFile.ReadLine()) != null)
{
Match myMatch = Regex.Match(line, @".*\|.*\|.*\|\|.*");
if (!myMatch.Success)
{
outFile.WriteLine(line);
}
}
inFile.Close();
outFile.Close();
//// Suspend the screen.
//Console.ReadLine();
}
}
}
这不起作用。我认为这是因为 RegEx 是“贪婪的”——如果有任何空白单元格,这匹配,因为我没有明确地说“捕获除了管道字符之外的所有内容”。快速搜索一下,我发现我可以在模式中使用 [^\|] 来做到这一点。
所以,如果我将模式更改为:
".*[^\|]\|.*[^\|]\|.*[^\|]\|\|.*"
为什么这也不起作用?
猜我有点困惑,任何指针将不胜感激。
谢谢!
【问题讨论】:
-
你对我来说太快了——我注意到了这一点并进行了相应的编辑。不幸的是,我的模式仍然无法正常工作。谢谢
-
这里有什么需要使用正则表达式的原因吗?在我看来,像
string.IsNullOrEmpty(line.Split('|')[2])这样的操作会容易得多。 -
第 3 项是从 1 还是从 0? =)
-
感谢@Maslow - 为了澄清,我编辑到第四位
-
@MagnusGrindalBakken 我真的很想了解更多关于正则表达式的信息,但你是对的 - 拆分将是这里最简单的解决方案
标签: c# regex regex-greedy