.NET Regex删除引号中的换行符

本文关键字:换行符 Regex 删除 NET | 更新日期: 2023-09-27 17:59:10

我正试图清理一个文本文件,以便将其导入Excel,但该文本文件在几个双引号字段中包含换行符。该文件以制表符分隔。

例如:

"12313"'t"1234"'t"123
5679"
"test"'t"test"'t"test"
"test"'t"test"'t"test"
"12313"'t"1234"'t"123
5679"

我需要删除换行符,这样它最终会显示为:

"12313"'t"1234"'t"1235679"
"test"'t"test"'t"test"
"test"'t"test"'t"test"
"12313"'t"1234"'t"1235679"

"''t"是制表符分隔符。

我看过SO上的其他几个解决方案,但它们似乎不处理多行。我们已经尝试使用了几种CSV解析器解决方案,但似乎无法使它们适用于此场景。目标是将整个字符串传递到REGEX表达式中,并使其返回时去掉引号之间的所有换行符,同时保留引号外的换行符。

.NET Regex删除引号中的换行符

您可以使用以下正则表达式:

(?!(([^"]*"){2})*[^"]*$)'n+

工作演示

这一个匹配一个或多个换行符,这些换行符后面没有偶数引号(它假设数据中没有转义异常)。

这对我有效:

var fixedCsvFileContent = Regex.Replace(csvFileContent, @"(?!(([^""]*""){2})*[^""]*$)'n+", string.Empty);

这个不起作用

var fixedCsvFileContent = Regex.Replace(csvFileContent, @"(?!(([^""]*""){2})*[^""]*$)'n+", string.Empty, RegexOptions.Multiline);

因此,不能添加RegexOptions。检查输入字符串时使用多行。

如果只删除空行有效:

string text = Regex.Replace( inputString, @"'n'n", "" , RegexOptions.None | RegexOptions.Multiline );

我遇到过类似的问题,但其中一些文件可能非常大。因此,在所有内容上使用RegEx将是一个沉重的解决方案,相反,我想尝试制作一个有点像ReadLine的东西,只是它会忽略引号中的特征线。这就是我正在使用的解决方案。

它是StreamReader类的扩展,用于读取CSV文件,与这里的一些RegEx解决方案一样,它确保有偶数个引号。因此,它使用ReadLine,检查是否有奇数个引号,如果有,它会执行另一个ReadLine,直到引号的数量为偶数:

    public static class Extensions
{
    public static string ReadEntry(this StreamReader sr)
    {
        string strReturn = "";
        //get first bit
        strReturn += sr.ReadLine();
        //And get more lines until the number of quotes is even
        while (strReturn.GetNumberOf("'"").IsOdd())
        {
            string strNow = sr.ReadLine();
            strReturn += strNow;
        }
        //Then return what we've gotten
        if (strReturn == "")
        {
            return null;
        }
        else
        {
            return strReturn;
        }
    }
    public static int GetNumberOf(this string s, string strSearchString)
    {
        return s.Length - s.Replace(strSearchString, "").Length;
    }
    public static Boolean IsOdd(this int i)
    {
        return i % 2 != 0;
    }
}
string output = Regex.Replace(input, @"(?<=[^""])'r'n", string.Empty);

使用提供的输入进行演示