在引号外的换行符上进行Regex拆分



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

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

第1排:bla-bla,12345。。。

第2行:";bla

bla";,12345。。。

第3排:bla-bla,12345。。。

我尝试使用类似文章中的regex,将逗号替换为换行符:,在没有双引号的逗号上进行拆分(在逗号外引号上进行拆分(

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

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

这里有两种方法。

#1

您可以匹配正则表达式

[^"rn]+(?:"[^"]*"[^"rn]+)*

演示

这个表达式可以分解如下。

[^"rn]*    # 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   
[^"rn]+  # 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/

启动发动机!

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

最新更新