我是相当新的使用正则表达式,并根据我读过一些教程,我不能让我的Regex.Replace格式正确此步骤。
下面是我的工作……当我拉从列表框中我的数据,我想它格式化为CSV喜欢的格式,然后保存文件的情况。使用Replace选项是这种情况的理想解决方案吗?
在正则表达式格式化示例之前。
FirstName LastName Salary Position ------------------------------------- John Smith $100,000.00 M
正则表达式替换后的格式
John Smith,100000,M
当前格式化状态输出:
John,Smith,M
*注意 – 有没有办法用空格替换第一个逗号?
我的代码片断
using(var fs = new FileStream(filepath,FileMode.OpenOrCreate,FileAccess.Write)) { using(var sw = new StreamWriter(fs)) { foreach (string stw in listBox1.Items) { StringBuilder sb = new StringBuilder(); sb.AppendLine(stw); //Piecing the list back to the original format sb_trim = Regex.Replace(stw,@"[$,]",""); sb_trim = Regex.Replace(sb_trim,@"[.][0-9]+",@"\s",","); sw.WriteLine(sb_trim); } } }
你可以用两个替换来做到这一点
//let stw be "John Smith $100,000.00 M" sb_trim = Regex.Replace(stw,@"\s+\$|\s+(?=\w+$)","); //sb_trim becomes "John Smith,100,000.00,M" sb_trim = Regex.Replace(sb_trim,@"(?<=\d),(?=\d)|[.]0+(?=,)",""); //sb_trim becomes "John Smith,M" sw.WriteLine(sb_trim);