c# - C#中的正则表达式替换

标签 c# regex

我对使用正则表达式还很陌生,根据我阅读的一些教程,我无法在我的 Regex.Replace 中正确格式化这一步。

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

在正则表达式格式化示例之前。

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

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

John Smith,100000,M

当前格式化状态输出:

John,Smith,100000,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]+", "");
            sb_trim = Regex.Replace(sb_trim, @"\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,100000,M"

sw.WriteLine(sb_trim);

关于c# - C#中的正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16117043/

相关文章:

c# - 进行异步调用时出现 NullReferenceException,但进行同步调用时则不会出现 NullReferenceException

php - .htaccess 前 3 个字符作为文件夹

javascript - 查找正则表达式搜索/匹配的结束索引

javascript - 荷兰邮政编码的正则表达式

c# - 如何使用 .NET 在内存中动态创建 jpg 图像?

c# - 如何使用 VS 调试服务器实现基本的 HTTP 身份验证?

c# - EntityFramework 中的 "HasPrecision"问题(版本=6.1.3)

c# - 如何在不触发 PageSizeChanged 事件的情况下以编程方式设置 RadGrid 的页面大小

python - 正则表达式:python 其他结果作为 regexr

regex - 使用 sed 替换 URL 模式失败