【问题标题】:Remove newlines inside quotation marks with Regex in C# [duplicate]在 C# 中使用正则表达式删除引号内的换行符 [重复]
【发布时间】:2018-03-13 06:56:10
【问题描述】:

我需要删除 csv 文件中引号内的一些不需要的换行符。

输入文件如下例所示:

0433000007880;2;text SOME TEXT;9;TOT 
0556000007880;5;SOME TEXT;6;"ECG


             22.54 "
0556000007880;6;some other text;2;00535

期望的输出:

0433000007880;2;text SOME TEXT;9;TOT 
0556000007880;5;SOME TEXT;6;"ECG 22.54 "
0556000007880;6;some other text;2;00535

现在,引号可以通过"[^"]*" 来识别,如this post 中所述。我缺少的是如何替换正则表达式匹配中的新行。

【问题讨论】:

  • CSV 中不能有文字双引号吗?喜欢12;"text ""in quotes"" and more";456
  • 正如@WiktorStribiżew 所说,我需要一把 12 英寸的尺子......
  • 在您的示例中,您不仅删除了换行符,还删除了引号......对吗?
  • @WiktorStribiżew 这是我得到的输入。由于引号,一些记录被分成多行。
  • @Fildor 你是对的,但这不是我主要关心的问题。我修改了这个问题。好点,谢谢

标签: c# regex


【解决方案1】:

您可以将正则表达式方法与Trim() 方法结合使用来获得结果。 首先,用"[^"]* 正则表达式捕获空行,然后用另一个正则表达式替换空格并在结果上调用Trim()

string Sanitize(string line)
{
    if(!Regex.IsMatch(line, @"""[^""]*"))
        return line;

    string pattern = @"\s+|"""; // <-- match multiple spaces or " character
    Regex regex = new Regex(pattern, RegexOptions.Multiline);
    string replacement = @" ";
    // replace matched strings with a single space
    var replaced = regex.Replace(line, replacement);
    // since " at the beginning and end of the string 
    // are replaced by spaces, trim those spaces before returning
    return replaced.Trim();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多