2013-05-19 14 views
3

我有以下字符串:如何在「[abc]」這樣的比賽中排除「[」和「]」?

[a] [abc] test [zzzz] 

我試圖讓這樣一個數組:

[0] => a 
[1] => abc 
[2] => zzzz 

我試過下面的代碼:

var string = '[a] [abc] test [zzzz]'; 
var matches = string.match(/\[(.*?)\]/g); 
for(var i = 0; i < matches.length; i++) 
    console.log(matches[i]); 

但我控制檯輸出顯示:

[a] 
[abc] 
[zzzz] 

我嘗試添加兩個非捕獲組(?:),像這樣:

var matches = string.match(/(?:\[)(.*?)(?:\])/g); 

但我看到同樣的比賽,持平。

怎麼回事,我該如何得到我想要的數組?

+0

你在正確的軌道上稍快運行。 [(。*)]將匹配您要查找的令牌,但這些令牌具有方括號。之後請刪除括號。 – bengoesboom

+0

這就是爲什麼我很傷心,JavaScript不支持lookbehinds。 '/(?<\[).*?(?=\])/''比黑客要容易得多。 –

+0

@Kolink非捕獲的表達式看起來更好IMO。 '(?:\ [{1}(?。*)\] {1})' – Phill

回答

3

match不捕獲全局匹配中的組。我爲這個目的做了一個小幫手。

String.prototype.gmatch = function(regex) { 
    var result = []; 
    this.replace(regex, function() { 
    var matches = [].slice.call(arguments,1,-2); 
    result.push.apply(result, matches); 
    }); 
    return result; 
}; 

而且使用它像:

var matches = string.gmatch(/\[(.*?)\])/g); 
0

正則表達式

[[]\s*(\b[^]]*\b)\s*[\]]

組1將包含您的打開和關閉括號之間的所有文本字符串數組

僅限正則表達式示例

比賽將撤出所有匹配的子串並顯示出來,因爲這僅使用正則表達式,它會然後用切片

var re = /[[]\s*(\b[^]]*\b)\s*[\]]/; 
    var sourcestring = "source string to match with pattern"; 
    var results = []; 
    var i = 0; 
    for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) { 
    results[i] = matches; 
    for (var j=0; j<matches.length; j++) { 
     alert("results["+i+"]["+j+"] = " + results[i][j]); 
    } 
    i++; 
    } 


(
    [0] => Array 
     (
      [0] => [a] 
      [1] => [abc] 
      [2] => [zzzz] 
     ) 

    [1] => Array 
     (
      [0] => a 
      [1] => abc 
      [2] => zzzz 
     ) 

)