簡體   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