var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
我希望数组是这样的:
var astr = ["single", "words", "fixed string of words"];
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
我希望数组是这样的:
var astr = ["single", "words", "fixed string of words"];
接受的答案并不完全正确。它分隔非空格字符,如 . 和 - 并在结果中留下引号。执行此操作以排除引号的更好方法是使用捕获组,例如:
//The parenthesis in the regex creates a captured group within the quotes
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = 'single words "fixed string of words"';
var myArray = [];
do {
//Each call to exec returns the next regex match as an array
var match = myRegexp.exec(myString);
if (match != null)
{
//Index 1 in the array is the captured group if it exists
//Index 0 is the matched text, which we use if no captured group exists
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);
myArray 现在将包含 OP 要求的内容:
single,words,fixed string of words
str.match(/\w+|"[^"]+"/g)
//single, words, "fixed string of words"
这使用了拆分和正则表达式匹配的混合。
var str = 'single words "fixed string of words"';
var matches = /".+?"/.exec(str);
str = str.replace(/".+?"/, "").replace(/^\s+|\s+$/g, "");
var astr = str.split(" ");
if (matches) {
for (var i = 0; i < matches.length; i++) {
astr.push(matches[i].replace(/"/g, ""));
}
}
这将返回预期的结果,尽管单个正则表达式应该能够完成所有操作。
// ["single", "words", "fixed string of words"]
更新 这是S.Mark提出的方法的改进版本
var str = 'single words "fixed string of words"';
var aStr = str.match(/\w+|"[^"]+"/g), i = aStr.length;
while(i--){
aStr[i] = aStr[i].replace(/"/g,"");
}
// ["single", "words", "fixed string of words"]
这里可能是一个完整的解决方案:https : //github.com/elgs/splitargs
ES6 解决方案支持:
代码:
str.match(/\\?.|^$/g).reduce((p, c) => {
if(c === '"'){
p.quote ^= 1;
}else if(!p.quote && c === ' '){
p.a.push('');
}else{
p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
}
return p;
}, {a: ['']}).a
输出:
[ 'single', 'words', 'fixed string of words' ]