2013-04-28 56 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' ] 
相關問題