Regex.replace 和 TrimEnd 功能合二为一
本文关键字:功能 合二为一 TrimEnd replace Regex | 更新日期: 2023-09-27 17:55:57
我似乎遇到了心理障碍,希望有人能指出我正确的方向。我有一个 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(',');
谢谢!
而不是执行 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(',');
}
我不知道
您可以在一个替换语句中做到这一点,但另一种方法是拆分并重新加入:
newLines = Sting.Join(
AllLines.Split(new [] {','},StringSplitOptions.RemoveEmptyEntries)
,",");
您可以使用正面查找前面有逗号的逗号或字符串末尾的逗号:
newLines = Regex.Replace(AllLines, "(?<=,),+|,+$", "", RegexOptions.Multiline);