Javascript将空格或引号上的字符串拆分为数组

IT技术 javascript regex split
2021-03-14 09:10:14
var str = 'single words "fixed string of words"';
var astr = str.split(" "); // need fix

我希望数组是这样的:

var astr = ["single", "words", "fixed string of words"];
6个回答

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

//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
效果很好,谢谢。只是说“i”开关看起来是多余的。
2021-04-23 09:10:14
我发布了一个问题,询问确切的问题,后来在更专门的搜索找到了这个很好的答案后删除了它(没有回复/答案)。如上所述,上面的解决方案完全符合 OP 的要求('apple banana "nova scotia" "british columbia"'>> "apple", "banana", "nova scotia", "british columbia"-- 我学到了一些新的 viz-a-viz JavaScript!:-)
2021-04-24 09:10:14
var myRegexp = [^\s"]+|"(?:\\"|[^"])*"/g ...允许\"(引号内的转义引号)
2021-05-15 09:10:14
str.match(/\w+|"[^"]+"/g)

//single, words, "fixed string of words"
如果它必须处理转义引号,则还有另一个问题。例如: 'single words "fixed string of \"quoted\" words"' 即使使用 Awalias 的更正,这["single", "words", ""fixed", "string", ""of", "words""] 也会给出: 您需要处理转义的引号,但不能绊倒并抓住并转义反斜杠。我认为它最终会变得比使用正则表达式真正想要处理的更复杂。
2021-04-23 09:10:14
@Awalias 我在下面有一个更好的答案。您的正则表达式示例实际上应该是 /[^\s"]+|"([^"]*)"/g。你的仍然会在引用区域的空格上分开。我添加了一个解决此问题的答案,并从 OP 要求的结果中删除了引号。
2021-04-24 09:10:14
这似乎在 '.' 上分裂 和 '-' 以及空格。这应该是str.match(/\S+|"[^"]+"/g)
2021-05-02 09:10:14
如果您想允许转义引号,请参阅其他 SO 问题
2021-05-08 09:10:14

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

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"]
改进版本存在一个问题,如果您使用像“#”这样的非单词字符,它将消失。
2021-04-28 09:10:14
这是一个很好的答案,但是如果您想通过正则表达式完成所有操作并删除引号,我添加了一个新答案来执行此操作,并且不需要遍历每个结果以在之后删除引号。
2021-04-30 09:10:14

这里可能是一个完整的解决方案: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' ]