2

我正在使用 StreamReader 将 CSV 文件的每一行读入一个字符串。在处理每一行时,我需要去掉任何只被其他数字包围的逗号。

例如,如果字符串是:

"textfield1", "textfield2", "100.00", "1,070.00"

我只需要从整个字符串中取出“1,070.00”中的逗号,结果是:

"textfield1", "textfield2", "100.00", "1070.00"

从 CSV 文件读取的每个字符串在字段数、长度等方面都可能不同,因此我需要使用一些东西(也许是正则表达式?)来查看整个字符串,而无需硬编码位置或全部删除所有逗号。

这是我一直在尝试的方法:

StreamReader sr = new StreamReader(strInputFile);
string nextLine = sr.ReadLine();     

try
{
    while ((nextLine = sr.ReadLine()) != null)
    {
        string rawtext = nextLine.Replace("[0-9]"+","+"[0-9]" , "[0-9]"+"[0-9]");

        // ....rest of code
    }
}

这显然不起作用,因为我不明白如何做到这一点:)
我是 C# 新手,对正则表达式没有经验,所以希望这相对简单。

4

1 回答 1

5

听起来您想使用正则表达式:

string rawtext = Regex.Replace(nextLine, @"(\d),(\d)", "$1$2");

或者这个等价的模式:

string rawtext = Regex.Replace(input, @"(?<=\d),(?=\d)", "");
于 2013-06-26T16:20:07.177 回答