C#中的正则表达式替换 [英] Regular expression replace in C#

查看:74
本文介绍了C#中的正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用正则表达式还很陌生,根据我读过的一些教程,我无法在Regex.Replace中正确设置格式.

I'm fairly new to using regular expressions, and, based on a few tutorials I've read, I'm unable to get this step in my Regex.Replace formatted properly.

这是我正在处理的方案...当我从列表框中提取数据时,我想将其格式化为 CSV 之类的格式,然后保存文件.对于这种情况,使用替换"选项是否是理想的解决方案?

Here's the scenario I'm working on... When I pull my data from the listbox, I want to format it into a CSV like format, and then save the file. Is using the Replace option an ideal solution for this scenario?

在使用正则表达式格式化示例之前.

Before the regular expression formatting example.

FirstName LastName Salary    Position
-------------------------------------
John      Smith    $100,000.00  M

正则表达式替换后的建议格式

Proposed format after regular expression replace

John Smith,100000,M

当前格式化状态输出:

John,Smith,100000,M

*注意-有什么方法可以用空格替换第一个逗号吗?

*Note - is there a way I can replace the first comma with a whitespace?

我的代码段

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]+", "");
            sb_trim = Regex.Replace(sb_trim, @"\s", ",");
            sw.WriteLine(sb_trim);
        }
    }
}

推荐答案

您可以使用两个replaces

You can do it this with two replace's

//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,100000,M"

sw.WriteLine(sb_trim);

这篇关于C#中的正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆