【问题标题】:Regex splitting on newline outside of quotes正则表达式在引号之外的换行符上拆分
【发布时间】:2022-04-26 12:10:19
【问题描述】:

我想在不在双引号内的新行上拆分数据流。该流包含多行数据,其中每一行由换行符分隔。但是,数据行可能包含双引号内的换行符。这些换行符并不表示下一行数据已经开始,所以我想忽略它们。

所以数据可能看起来像这样:

第 1 行:bla bla,12345,...

第 2 行:"bla

bla", 12345, ...

第 3 行:bla bla,12345,...

我尝试使用类似帖子中的正则表达式,通过用换行符替换逗号来拆分逗号而不是用双引号 (Splitting on comma outside quotes):

\n(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)

这个正则表达式与我期望的不匹配。我错过了什么吗?

【问题讨论】:

标签: javascript regex


【解决方案1】:

这里有两种方法。

#1

可以匹配正则表达式

[^"\r\n]+(?:"[^"]*"[^"\r\n]+)*

Demo

表达式可以分解如下。

[^"\r\n]*    # match zero or more characters other than those in the
             # character class
(?:          # begin non-capture group
  "[^"]*"    # match double-quote followed by zero or more characters
             # other than a double-quote, followed by a double-quote   
  [^"\r\n]+  # match zero or more characters other than those in the
             # character class
)*           # end non-capture group and execute it zero or more times

#2

匹配不在双引号之间的行终止符等效于匹配行终止符,从字符串的开头开始,前面有偶数个双引号。您可以使用以下正则表达式匹配此类行终止符(未设置多行标志,以便^ 匹配字符串的开头,而不是行的开头)。

/(?<=^[^"]*(?:"[^"]*"[^"]*)*)\r?\n/

Start your engine!

Javascript 的正则表达式引擎(令人印象深刻地支持可变长度的lookbehinds)执行以下操作。

(?<=         : begin positive lookbehind
  ^          : match beginning of string (not line)
  [^"]*      : match 0+ chars other than '"'
  (?:        : begin non-capture group
    "[^"]*"  : match '"', 0+ chars other than '"', '"'
    [^"]*    : match 0+ chars other than '"' 
  )*         : end non-capture group and execute 0+ times
)            : end positive lookbehind
\r?\n        : match line terminator

【讨论】:

    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 2021-11-14
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多