2013-04-28 57 views
22

我需要帮助在javascript中用空格(“”)分隔字符串,忽略引号表达式中的空格。javascript空格分隔字符串,但忽略引号中的空格(注意不要通过冒号拆分)

我有这个字符串:

var str = 'Time:"Last 7 Days" Time:"Last 30 Days"'; 

我希望我的字符串被分割为2:

['Time:"Last 7 Days"', 'Time:"Last 30 Days"'] 

,但我的代码分割为4:

['Time:', '"Last 7 Days"', 'Time:', '"Last 30 Days"'] 

这是我的代码:

str.match(/(".*?"|[^"\s]+)(?=\s*|\s*$)/g); 

谢谢!

+0

虽然链接的问题是_related_ ,它不是重复的:_这个问题明确地要求直接与double-qu相邻的未加引号的字符串(例如'foo:“bar none”')被识别为_single_标记(并且没有提及需要处理转义的双引号)。 – mklement0 2015-10-09 15:30:30

回答

51
s = 'Time:"Last 7 Days" Time:"Last 30 Days"' 
s.match(/(?:[^\s"]+|"[^"]*")+/g) 

// -> ['Time:"Last 7 Days"', 'Time:"Last 30 Days"'] 

解释:

(?:   # non-capturing group 
    [^\s"]+ # anything that's not a space or a double-quote 
    |   # or… 
    "   # opening double-quote 
    [^"]* # …followed by zero or more chacacters that are not a double-quote 
    "   # …closing double-quote 
)+   # each match is one or more of the things described in the group 

事实证明,解决您的原始表达式,你只需要在组中添加+

str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g) 
#      ^here. 
+1

如果你解释了常规的表达。 – 2013-04-28 09:58:42

+0

首先得到它。 – kch 2013-04-28 10:00:08

+0

谢谢!作品!和超快速回复:-) – user1986447 2013-04-28 10:45:46

0

ES6解决方案,支持:

  • 按空格拆分除了f或引号内
  • 去掉引号,而不是反斜线报价
  • 逃逸报价成为报价

代码:

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 

输出:

[ 'Time:Last 7 Days', 'Time:Last 30 Days' ] 
相关问题