regex 特定字符串的正则表达式无效

oxcyiej7  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(216)

我有一个这样的字符串:

let input  = "Bldg ,32.9,-117.11,Yes,California,Yes,San Diego,,"San Diego, CA",123"

我需要根据逗号(“,”)分割字符串,但引号中的逗号应该被忽略。我试图应用正则表达式,但在这种情况下,空白值消失了。
我需要以下输出

["Bldg",
"32.9", 
"-117.11", 
"Yes",
"California",
"Yes",
"San Diego",
"",
"San Diego, CA",
"123"
]

我已经应用了下面的regex -/[^",]+|"([^"]*)"/g,但这不起作用。

hk8txs48

hk8txs481#

可以匹配正则表达式

(?<=")[^"]*(?=")|(?<![^,])[^,"]*(?![^,])

Demo
这场比赛的结果如下。

["Bldg ", "32.9", "-117.11", "Yes", "California",
 "Yes", "San Diego", "", "San Diego, CA", "123"]

正则表达式具有以下元素。

(?<=")      positive lookbehind asserts that previous character is a double-quote
[^"]*       match zero or more characters other than double quotes
(?=")       positive lookahead asserts that next character is a double-quote
|           or
(?<![^,])   negative lookbehind asserts that previous character is not a
            character other than a double-quote
[^,"]*      match zero or more characters other than commas and double-quotes
(?![^,])    negative lookahead asserts that next character is not a
            character other than a double-quote

请注意,双否定,“负向后查找Assert前一个字符不是双引号以外的字符”等同于Assert前一个字符是双引号或当前字符位于字符串的开头。类似地,“负先行Assert下一个字符不是双引号以外的字符”等效于Assert下一个字符是双引号字符串的结尾是字符串的结尾。

相关问题