2010-05-12 22 views

回答

25
​​
+3

這似乎分裂'。'和' - '以及空格。這應該可能是'str.match(/ \ S + |「[^」] +「/ g)' – Awalias 2013-04-09 13:22:47

+0

如果需要處理轉義引號,還有另外一個問題,例如: 」單個單詞「即使有Awalias的更正,這也給出了: '[「single」,「words」,「」fixed「,」string「,」「of」,「words」的字符串「 「」]' 您需要處理轉義引號,但不能跳轉並獲取並轉義反斜線。我認爲它最終會比你真正想用正則表達式處理更復雜。 – jep 2013-06-20 14:55:18

+0

@Awalias我在下面有一個更好的答案。你的正則表達式實例應該是/ [^ \ s「] + |」([^「] *)」/ g。你們仍然會在引用區域的空間分割。我添加了一個解決此問題的答案,並從OP所要求的結果中刪除引號。 – dallin 2013-09-06 00:02:20

9

這使用了split和regex匹配的混合。

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"] 
+0

謝謝,我打算改進版本 – Remi 2010-05-12 10:23:14

+0

改進後的版本存在問題,如果使用「#」之類的非字字符,它將會消失。 – tuhoojabotti 2012-06-26 22:03:37

+0

這是一個很好的答案,但如果你想通過正則表達式完成所有的操作,並且刪除了引號,我添加了一個新的答案,並且不需要循環遍歷每個結果以後去除引號。 – dallin 2013-09-06 00:25:04

0

提出的方法的改進版,我注意到消失的人物了。我認爲你可以包含它們 - 例如,讓它包含「+」這個詞,使用類似「[\ w \ +]」的名稱而不是「\ w」。

13

接受的答案不完全正確。它分隔非空間字符,如。並且 - 在結果中留下引號。更好的方式來做到這一點,以便它不包括引號是捕獲組,像這樣的:

//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 
+0

很好,謝謝。只是說'我'開關看起來是多餘的。 – 2016-07-12 15:20:58

1

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' ] 
相關問題