繁体   English   中英

.NET 正则表达式删除引号内的换行符

[英].NET Regex To Remove Line Breaks Within Quotes

我正在尝试清理文本文件,以便可以将其导入 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 表达式中,并让它返回,同时删除引号之间的所有换行符,而保留引号外的换行符。

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

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

工作演示

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

string output = Regex.Replace(input, @"(?<=[^""])\r\n", string.Empty);

提供输入的演示

如果仅删除空白行即可:

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

这为我工作:

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

没有用

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

因此,在对输入字符串进行检查时,不得添加RegexOptions.Multiline。

我遇到了类似的问题,但有些文件可能真的很大。 因此,在所有内容上使用 RegEx 将是一个繁重的解决方案,相反,我想尝试制作一些类似于 ReadLine 的东西,只是它会忽略引号内的断线。 这是我正在使用的解决方案。

它是 StreamReader class 的扩展,用于读取 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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM