Regex.replace和TrimEnd功能合二为一

时间:2013-01-25 18:32:22

标签: c# visual-studio-2010 trim

我似乎已经打了精神障碍,希望有人能指出我正确的方向。我有一个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(',');

谢谢!

3 个答案:

答案 0 :(得分:1)

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

newLines = Sting.Join(
               AllLines.Split(new [] {','},StringSplitOptions.RemoveEmptyEntries)
              ,",");

答案 1 :(得分: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(',');
}

答案 2 :(得分:0)

您可以使用正面的lookbehind来查找以逗号开头的逗号,或者在字符串末尾的逗号:

newLines = Regex.Replace(AllLines, "(?<=,),+|,+$", "", RegexOptions.Multiline);
相关问题