2011-08-26 18 views
11

ho la seguente stringa: pass[1][2011-08-21][total_passes]Regex per afferrare le stringhe tra parentesi quadre

Come dovrei estrarre gli elementi tra le parentesi quadre in un array? Ho provato

match(/\[(.*?)\]/);

var s = 'pass[1][2011-08-21][total_passes]'; 
 
var result = s.match(/\[(.*?)\]/); 
 

 
console.log(result);

ma questo solo restituisce [1].

Non so come fare .. Grazie in anticipo.

risposta

27

siete quasi arrivati, basta un global match (nota la bandiera /g):

match(/\[(.*?)\]/g); 

Esempio: http://jsfiddle.net/kobi/Rbdj4/

Se si desidera qualcosa che cattura solo il gruppo (da MDN):

var s = "pass[1][2011-08-21][total_passes]"; 
var matches = []; 

var pattern = /\[(.*?)\]/g; 
var match; 
while ((match = pattern.exec(s)) != null) 
{ 
    matches.push(match[1]); 
} 

Esempio: http://jsfiddle.net/kobi/6a7XN/

Un'altra opzione (che io di solito preferisco), sta abusando il callback sostituire:

var matches = []; 
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);}) 

Esempio: http://jsfiddle.net/kobi/6CEzP/

+0

Questo restituisce le stringhe che desidero, ma sono ancora tra parentesi – Growler

+0

Non riesco a analizzare il contenuto dell'array in multiline. Ecco l'esempio. 'export const routes: Routes = [ {path: '', pathMatch: 'full', redirectTo: 'tree'}, {path: 'components', redirectTo: 'components/tree'}, {path: ' components/tree ', component: CstdTree}, {path:' components/chips ', componente: CstdChips} ]; –

0

aggiungere il flag globale al vostro regex, e iterare la matrice restituita.

match(/\[(.*?)\]/g) 
4
var s = 'pass[1][2011-08-21][total_passes]'; 

r = s.match(/\[([^\]]*)\]/g); 

r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ] 

example proving the edge case of unbalanced []; 

var s = 'pass[1]]][2011-08-21][total_passes]'; 

r = s.match(/\[([^\]]*)\]/g); 

r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ] 
-1

[C#]

 string str1 = " pass[1][2011-08-21][total_passes]"; 
     string matching = @"\[(.*?)\]"; 
     Regex reg = new Regex(matching); 
     MatchCollection matches = reg.Matches(str1); 

è possibile utilizzare foreach per le stringhe corrispondenti.

0

Non sono sicuro di poterlo inserire direttamente in un array. Ma il seguente codice dovrebbe lavorare per trovare tutte le occorrenze e poi elaborarli:

var string = "pass[1][2011-08-21][total_passes]"; 
var regex = /\[([^\]]*)\]/g; 

while (match = regex.exec(string)) { 
    alert(match[1]); 
} 

Si prega di notare: Credo davvero che è necessario la classe [^ \]] qui. Altrimenti nel mio test l'espressione corrisponderebbe alla stringa del buco perché] corrisponde anche a. *.

Problemi correlati