我有一个这样的字符串:
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
,但这不起作用。
可以匹配正则表达式
(?<=")[^"]*(?=")|(?<![^,])[^,"]*(?![^,])
演示匹配的结果如下:
["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
注意,双引号"否定"后置断言前一个字符不是双引号"以外的字符。相当于断言前一个字符是双引号,或者当前字符位于字符串的开头。类似地,"反向前看"断言下一个字符不是双引号以外的字符;相当于断言下一个字符是双引号,或者当前字符位于字符串的末尾。