gpt4 book ai didi

javascript - 按空格拆分 Javascript,除非在引号之间——但不匹配引号本身

转载 作者:行者123 更新时间:2023-11-30 11:56:15 25 4
gpt4 key购买 nike

这是一个常见问题的轻微变体:如何用空格分隔字符串,除非空格包含在一对引号("或 ')中?这里有很多这样的问题,而到目前为止,我找到的最佳答案是 this one。问题是,所有这些答案都在匹配项中包含引号本身。例如:

"foo bar 'i went to a bar'".match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);

结果:

["foo", "bar", "'i went to a bar'"]

是否有解决方案导致:

["foo", "bar", "i went to a bar"]

注意这里有一个边缘案例:

"foo bar \"'Hi,' she said, 'how are you?'\"".match(...);
=> // ["foo", "bar", "'Hi,' she said, 'how are you?'"]

也就是说,一个子字符串应该能够包含它自己的引号,这意味着激进地做这样的事情是行不通的:

"foo bar \"'Hi,' she said, 'how are you?'\"".match(...).map(function(string) {
return string.replace(/'|"/g, '');
});

更新:

我们基本上可以让它工作:

"foo bar \"'Hi,' she said, 'how are you?'\"".match(/[^\s"']+|"([^"]*)"|'([^']*)'/g).map(function(string) {
return string.replace(/^('|")|('|")$/g, '');
});

但这很丑陋。 (它还会打破像“5ft 5feet 5'”这样的边缘情况。)一定有办法将其缩小为单个正则表达式,对吧?

最佳答案

您的正则表达式足够好。您只需遍历匹配项并选择正确的捕获组:

var re = /'([^'\\]*(?:\\.[^'\\]*)*)'|"([^"\\]*(?:\\.[^"\\]*)*)"|[^\s"']+/g;
var arr = ['foo bar "\'Hi,\' she said, \'how are you?\'"',
'foo bar \'i went to a bar\'',
'foo bar \'"Hi," she said, "how are you?"\'',
'\'"Hi," she \\\'said\\\', "how are you?"\''
];

for (i = 0; i < arr.length; i++) {
var m;
var result = [];
while ((m = re.exec(arr[i])) !== null) {
if (m.index === re.lastIndex)
re.lastIndex++;
result.push(m[1] || m[2] || m[0])
}
console.log(result)
}

关于javascript - 按空格拆分 Javascript,除非在引号之间——但不匹配引号本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37866239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com