[英]Split a string by multiple delimiters and ignore delimiters in quotes javascript
I'm trying to write a regular expression to split a string into an array. 我正在尝试编写正则表达式以将字符串拆分为数组。 It must split using a delimiter of a space or comma, and ignore the delimiter inside of quoted phrases (using single or double quotes).
它必须使用空格或逗号的分隔符进行拆分,并忽略带引号的短语内部的分隔符(使用单引号或双引号)。
So far I'm able to get it to delimit by space and commas, but I'm unable to get it to ignore them between the quotation marks and I'm lost. 到目前为止,我可以通过空格和逗号来分隔它,但是我无法使它在引号之间忽略它们,我迷路了。
var pattern = /\b\w+[^"', ]+(?!'")/g,
text = "Hello world \"Boston Red Sox\" hello, world, \'boston, red sox\', \'beached whale\', pickup sticks",
output = text.match(pattern);
Current output: 电流输出:
["Hello", "world", "Boston", "Red", "Sox", "hello", "world", "boston", "red", "sox", "beached", "whale", "pickup", "sticks"]
Desired output: 所需的输出:
["Hello", "world", "Boston Red Sox", "hello", "world", "boston, red sox", "beached whale", "pickup", "sticks"]
Any help would be great! 任何帮助将是巨大的!
Just use |
只需使用
|
var regex = /"([^"]*)"|'([^']*)'|[^\\s,]+/g; var text = "Hello world \\"Boston Red Sox\\" hello, world, \\'boston, red sox\\', \\'beached whale\\', pickup sticks"; var output = []; var m; while ((m = regex.exec(text)) !== null) { output.push(m[1] || m[2] || m[0]); } console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.