如何用C#删除CSV文件中后缀递增的指定字符串?
解决方案:批量删除CSV中带递增数字后缀的指定字符串
问题说明
现有C#代码处理CSV时,只能删除固定后缀_0001的目标字符串,但实际场景中后缀会递增为_0002、_0003等,需要适配所有这类带4位数字后缀的目标字符串。
修改方案
使用正则表达式匹配目标字符串的固定前缀+可变4位数字后缀,替换为空字符串。需先添加System.Text.RegularExpressions命名空间引用。
修改后的完整代码
using System.Text.RegularExpressions; // 需添加此命名空间 private void button2_Click(object sender, EventArgs e) { try { if (String.IsNullOrEmpty(FromFile)) { lblStatus.Text = "Missing CSV Information"; Application.DoEvents(); MessageBox.Show("Please select CSV file first."); return; } if (String.IsNullOrEmpty(ToFile)) { lblStatus.Text = "Missing Save Information"; Application.DoEvents(); MessageBox.Show("Please enter save information."); return; } else if (File.Exists(ToFile)) { // delete old file File.Delete(ToFile); } btnProcess.Enabled = false; lblStatus.Text = "Processing..."; Application.DoEvents(); var lines = File.ReadAllLines(FromFile).Skip(1); string docId = ""; string[] oldLine = null; // 正则表达式:匹配固定前缀+4位数字后缀的目标字符串 var targetPattern = @"MEMBERRECORDS_SIGNATURECARD_00000000_00000000_\d{4}"; foreach (var line in lines) { // 替换逻辑:先处理引号、路径符号,再用正则替换可变后缀的目标字符串 var processedLine = line.Replace("\"", "").Replace(".\\", "").Replace("\\", ""); processedLine = Regex.Replace(processedLine, targetPattern, ""); var newLine = processedLine.Split(','); if (docId != newLine[0]) { docId = newLine[0]; oldLine = newLine; } else { for (int i = COPY_FROM - 1; i < newLine.Length; i++) newLine[i] = oldLine[i]; } using (StreamWriter sr = new StreamWriter(ToFile, true)) { sr.WriteLine(string.Join("|", newLine)); } } btnProcess.Enabled = true; lblStatus.Text = "Completed"; Application.DoEvents(); } catch (Exception ex) { MessageBox.Show("Error! Ex: " + ex.Message); } }
关键修改点
- 添加
using System.Text.RegularExpressions;引用,启用正则功能 - 定义正则模式
targetPattern:\d{4}匹配任意4位数字,覆盖所有_0001、_0002等递增后缀 - 将原固定字符串替换改为
Regex.Replace,批量处理所有符合格式的目标字符串
内容的提问来源于stack exchange,提问作者Ivonne Aspilcueta
相关产品推荐
相关产品推荐

