javascript在空格或数组引号上拆分字符串

Rem*_*emi 26 javascript regex split

var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix
Run Code Online (Sandbox Code Playgroud)

我希望数组如下:单个,单词,固定字符串.

YOU*_*YOU 27

str.match(/\w+|"[^"]+"/g)

//single, words, "fixed string of words"
Run Code Online (Sandbox Code Playgroud)

  • 这似乎分裂为'.' 和' - '以及空格.这应该是`str.match(/\S + |"[^"] +"/ g)` (4认同)
  • @Awalias 我在下面有一个更好的答案。您的正则表达式示例实际上应该是 /[^\s"]+|"([^"]*)"/g。你的仍然会在引用区域的空格上分开。我添加了一个解决此问题的答案,并从 OP 要求的结果中删除了引号。 (2认同)

dal*_*lin 24

接受的答案并不完全正确.它分隔非空格字符,如. - 并在结果中留下引号.执行此操作以便排除引号的更好方法是使用捕获组,如下所示:

//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);
Run Code Online (Sandbox Code Playgroud)

myArray现在将包含OP所要求的内容:

single,words,fixed string of words
Run Code Online (Sandbox Code Playgroud)

  • 效果很好,谢谢。只是说“ i”开关看起来是多余的。 (2认同)

Sea*_*sey 12

这使用了分割和正则表达式匹配的混合.

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, ""));
    }
}
Run Code Online (Sandbox Code Playgroud)

这会返回预期的结果,尽管单个正则表达式应该能够完成所有操作.

// ["single", "words", "fixed string of words"]
Run Code Online (Sandbox Code Playgroud)

更新 这是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"]
Run Code Online (Sandbox Code Playgroud)


小智 5

这可能是一个完整的解决方案: https ://github.com/elgs/splitargs