2012-03-30 8 views
1

Ich brauche eine Zeichenfolge wie [one, two, three, hello, foobar] anzupassen und zu extrahieren one, two, three, hello und foobar ist.RegEx - Match einfache Sammlung-Syntax und Extrakt Inhalt

Wie kann dies mit regulären Ausdrücken und Javascript erreicht werden?

Ich habe \[((\w+)\s*,?\s*)*\] versucht, aber dies auch [one two, three] für jedes Spiel (, fehlt) und ich weiß auch nicht, wie extrahieren die (\w+) Gruppe passen würde.

Antwort

2

Vielleicht so etwas?

var s = '[one, two, three, hello, fo obar]'; 
var words = s.replace(/^\s*\[\s*/, '') //remove [ 
      .replace(/\s*\]\s*$/, '') //remove ] 
      .split(/\s*,\s*/);  // split by comma 

Arbeitsbeispiel: http://jsbin.com/edijef

Natürlich, das wird noch komplizierter, wenn Sie ein Komma in Ihrem Text entkommen, da Spaltung ist nicht länger eine Option.