我正在寻找一些有关RegEx模式的指导。C#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是“贪婪” - 如果有空白单元格,就会匹配,因为我没有明确地说“除了管道字符之外的所有内容”。快速谷歌,我看到我可以在模式中使用[^ \ |]。
所以,如果我改变模式:
".*[^\|]\|.*[^\|]\|.*[^\|]\|\|.*"
为什么不这项工作要么?
猜猜我有点困惑,任何指针将不胜感激。
谢谢!
你对我来说太快了 - 我注意到了这一点,并做了相应的编辑。不幸的是我的模式仍然没有工作。 谢谢 – Ekins86
是否有某些原因需要在这里使用正则表达式?在我看来,像'string.IsNullOrEmpty(line.Split('|')[2])'这样的事情会更容易。 –
从1或从0开始的第3个项目? =) – Maslow