1

我似乎遇到了精神障碍,希望有人能指出我正确的方向。我有一个 csv 文件,它在值之间有许多逗号(随机),我有一些代码处理这个问题,它将两个逗号替换为一个等。看下面:

        using (StreamReader r = new StreamReader(tbFilePathName.Text))
        {
            string AllLines;
            string newLines;

            //This skips the first line.
            AllLines = r.ReadLine();

            //Reads all the lines to the end.
            AllLines = r.ReadToEnd();

            //This replaces all the instances of a double comma into a single comma. Effectively getting all the data into one column of the csv.
            newLines = Regex.Replace(AllLines, ",{2,}", ",").Trim(',');

            rtbViewLines.AppendText(newLines);

            r.Close();

但是我希望能够删除每行末尾的逗号,只在行内留下逗号。我怎样才能与下面的功能一起做到这一点?

 newLines = Regex.Replace(AllLines, ",{2,}", ",").Trim(',');

谢谢!

4

3 回答 3

1

我不知道您可以在一个替换语句中执行此操作,但另一种方法是拆分并重新加入:

newLines = Sting.Join(
               AllLines.Split(new [] {','},StringSplitOptions.RemoveEmptyEntries)
              ,",");
于 2013-01-25T18:38:12.690 回答
1

而不是 r.ReadToEnd() 循环遍历行并删除尾随逗号

老的

//Reads all the lines to the end.
AllLines = r.ReadToEnd();

新的

//Reads all the lines to the end.
while (r.Peek() >= 0)
{
    AllLines += r.ReadLine().TrimEnd(',');
}
于 2013-01-25T18:53:42.273 回答
0

您可以使用正向查找来查找逗号前面的逗号或字符串末尾的逗号:

newLines = Regex.Replace(AllLines, "(?<=,),+|,+$", "", RegexOptions.Multiline);
于 2013-01-25T18:39:50.113 回答