用逗号分隔字符串,但忽略引号内的逗号

Šim*_*das 11 javascript regex

示例字符串:

"Foo","Bar, baz","Lorem","Ipsum"
Run Code Online (Sandbox Code Playgroud)

这里我们用引号分隔4个引号值.

当我这样做:

str.split(',').forEach(…
Run Code Online (Sandbox Code Playgroud)

比那还要分割"Bar, baz"我不想要的价值.是否可以使用正则表达式忽略引号内的逗号?

hwn*_*wnd 42

一种方法是在这里使用Positive Lookahead断言.

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res);  // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
Run Code Online (Sandbox Code Playgroud)

正则表达式:

,               ','
(?=             look ahead to see if there is:
(?:             group, but do not capture (0 or more times):
(?:             group, but do not capture (2 times):
 [^"]*          any character except: '"' (0 or more times)
 "              '"'
){2}            end of grouping
)*              end of grouping
 [^"]*          any character except: '"' (0 or more times)
$               before an optional \n, and the end of the string
)               end of look-ahead
Run Code Online (Sandbox Code Playgroud)

或者是否定的前瞻

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
Run Code Online (Sandbox Code Playgroud)

  • 这也是我允许使用单引号的尝试!`str.split(/,(?=(?:(?:[^'"]*(?:'|")){2})*[^'"]*$)/)` 让我知道有错误。也需要改正! (2认同)