Split a string by whitespace, keeping quoted segments, allowing escaped quotes

前端 未结 4 1933
南方客
南方客 2020-11-28 09:27

I currently have this regular expression to split strings by all whitespace, unless it\'s in a quoted segment:

keywords = \'pop rock \"hard rock\"\';
keyword         


        
4条回答
  •  星月不相逢
    2020-11-28 09:42

    ES6 solution supporting:

    • Split by space except for inside quotes
    • Removing quotes but not for backslash escaped quotes
    • Escaped quote become quote
    • Can put quotes anywhere

    Code:

    keywords.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
    

    Output:

    [ 'pop', 'rock', 'hard rock', '"dream" pop' ]
    

提交回复
热议问题