2015-05-19 40 views
6

嗨我偶然發現了一個與我無法解決的正則表達式有關的問題。一個JavaScript正則表達式來標記查詢

我需要來標記查詢(分裂查詢轉換成份),假定下面的一個作爲示例:

These are the separate query elements "These are compound composite terms" 

我最終需要的是具有7個令牌的陣列:

1) These 
2) are 
3) the 
4) separate 
5) query 
6) elements 
7) These are compound composite term 

第七個標記由幾個單詞組成,因爲它位於雙引號內。

我的問題是:是否可以根據上述解釋使用一個正則表達式來相應地標記輸入字符串?

編輯

我很好奇使用Regex.exec或類似的代碼,而不是split同時實現同樣的事情的可能性,所以我做了一些調查得知,其次是another question here。所以作爲另一個問題的答案後面的正則表達式,可以用:

(?:")(?:\w+\W*)+(?:")|\w+ 

用下面的一行代碼的使用場景:

var tokens = query.match(/(?:")(?:\w+\W*)+(?:")|\w+/g); 

希望這將是有用的......

回答

5

你可以使用這個表達式:

var s = 'These are the separate query elements "These are compound composite term"'; 

var arr = s.split(/(?=(?:(?:[^"]*"){2})*[^"]*$)\s+/g); 
//=> ["These", "are", "the", "separate", "query", "elements", ""These are compound composite term""] 

此正則表達式將分裂的空間,如果這些是通過使用一個超前,以確保有偶數個引號的空間後,外面的雙引號。

+1

哦,我是想查詢的,而不是分割字符串... – Lu4

+0

的值,但在這種情況下,你身邊'「這些化合物的複合術語」'雙引號。我以爲你不需要報價。 –

+1

這也將工作,主要觀點是性能 – Lu4

2

您可以使用一個簡單的方法來分割字符串,並抓住雙引號內的子串,然後擺脫空數組項與clean功能:

Array.prototype.clean = function() { 
 
    for (var i = 0; i < this.length; i++) { 
 
    if (this[i] == undefined || this[i] == '') {   
 
     this.splice(i, 1); 
 
     i--; 
 
    } 
 
    } 
 
    return this; 
 
}; 
 

 
var re = /"(.*?)"|\s/g; 
 
var str = 'These are the separate query elements "These are compound composite term"'; 
 
var arr = str.split(re); 
 
alert(arr.clean());

2

可以獲得一個報價與下一個".*?"之間或不是空白的所有內容\S+

var re = /".*?"|\S+/g, 
 
    str = 'These are the separate query elements "These are compound composite term"', 
 
    m, 
 
    arr = []; 
 

 
while (m = re.exec(str)){ 
 
    arr.push(m[0]); 
 
} 
 
alert(arr.join('\n'));