【发布时间】:2014-12-10 17:25:59
【问题描述】:
我是 VB、C# 的新手,并且正在努力使用正则表达式。我想我有以下代码格式可以用我的文件中的空格替换正则表达式匹配。
编辑:每个 cmets,此代码块已更改。
var fileContents = System.IO.File.ReadAllText(@"C:\path\to\file.csv");
fileContents = fileContents.Replace(fileContents, @"regex", "");
regex = new Regex(pattern);
regex.Replace(filecontents, "");
System.IO.File.WriteAllText(@"C:\path\to\file.csv", fileContents);
我的文件格式如下:
"1111111","22222222222","Text that may, have a comma, or two","2014-09-01",,,,,,
到目前为止,我有正则表达式在 ," 和 ", 之间找到任何包含逗号的字符串(第一个或最后一个单元格中从来没有逗号,所以我不担心排除这两个。我在Expresso 中测试正则表达式
(?<=,")([^"]+,[^"]+)(?=",)
我只是不确定如何将该逗号分隔为需要替换的内容。最好的方法是什么?
已解决: 结合 [^"]+ 与后视/前视:
(?<=,"[^"]+)(,)(?=[^"]+",)
最终编辑: 这是我最终的完整解决方案:
//read file contents
var fileContents = System.IO.File.ReadAllText(@"C:\path\to\file.csv");
//find all commas between double quotes
var regex = new Regex("(?<=,\")([^\"]+,[^\"]+(?=\",)");
//replace all commas with ""
fileContents = regex.Replace(fileContents, m => m.ToString().Replace(",", ""));
//write result back to file
System.IO.File.WriteAllText(@"C:\path\to\file.csv", fileContents);
【问题讨论】:
-
Java 的同样问题:stackoverflow.com/questions/1757065/…
-
Filecontents.Replace 不会对初学者进行正则表达式替换。您创建一个正则表达式 regex = new Regex(pattern);然后你做 regex.Replace(filecontents, replacement);
-
@DStanley 我不想拆分字符串
-
@FlorianSchmidinger 感谢您的解释,我会这样尝试,但仍需要找出正确的正则表达式
-
@RichardN - 当您使用该正则表达式时,它只会找到它替换的单个字符。匹配评估器委托是一个昂贵的回调,其主要目的是对主要的一般替换进行子替换。使用相同的正则表达式,试试这个
Console.WriteLine(Regex.Replace(@",""one, two"",", "(?<=,\"[^\"]+),(?=[^\"]+\",)", ""));然后这个Console.WriteLine(Regex.Replace(@",""one, two"",", "(?<=,\"[^\"]+),(?=[^\"]+\",)", m => m.ToString().Replace(",", "")));
标签: c# regex visual-studio-2010 csv replace