【问题标题】:Regex to remove line break within double quote in CSV正则表达式删除 CSV 中双引号内的换行符
【发布时间】:2020-08-15 01:58:58
【问题描述】:

您好,我有一个 csv 文件,其中有错误。所以我希望它用正则表达式更正,一些字段包含换行符,示例如下

"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre Pkwy

California",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"

以上两行应该在一行

"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre PkwyCalifornia",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"

我尝试使用下面的正则表达式,但它没有帮助我

%s/\\([^\"]\\)\\n/\\1/

【问题讨论】:

  • 双引号内的换行符在 CSV 中是合法的(至少,在最常见的方言中,因为没有单一标准)。如果需要在字段中包含换行符,这是最常见的方式。只需将这些行粘贴在一起,您就是在破坏 Google 的地址。

标签: java regex string


【解决方案1】:

试试这个:

public static void main(String[] args) {
    String input = "\"AHLR150\",\"CDS\",\"-1\",\"MDCPBusinessRelationshipID\","
            + ",,\"Investigating\",\"1600 Amphitheatre Pkwy\n"
            + "California\",,\"Mountain View\",,\"United\n"
            + "States\",,\"California\",,,\"94043-1351\",\"9958\"\n";

    Matcher matcher = Pattern.compile("\"([^\"]*[\n\r].*?)\"").matcher(input);
    Pattern patternRemoveLineBreak = Pattern.compile("[\n\r]");

    String result = input;
    while(matcher.find()) {
        String quoteWithLineBreak = matcher.group(1);
        String quoteNoLineBreaks = patternRemoveLineBreak.matcher(quoteWithLineBreak).replaceAll(" ");
        result = result.replaceFirst(quoteWithLineBreak, quoteNoLineBreaks);
    }

    //Output
    System.out.println(result);
}

输出:

"AHLR150","CDS","-1","MDCPBusinessRelationshipID",,,"Investigating","1600 Amphitheatre Pkwy California",,"Mountain View",,"United States",,"California",,,"94043-1351","9958"

【讨论】:

    【解决方案2】:

    基于this,您可以尝试:

    /\r?\n|\r/
    

    我检查了here,似乎没问题

    【讨论】:

    • 他们只想删除引用字符串中的换行符,而不是所有个换行符。
    • @user12176589 它无法正常工作,因为我在您提供的链接中进行了检查,我只想删除双引号内的 \r\n
    猜你喜欢
    • 2013-08-27
    • 2020-01-07
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2018-10-29
    相关资源
    最近更新 更多