Danny Beckett
Danny Beckett

Reputation: 20806

How can I exclude "[" and "]" in a match like "[abc]"?

I have the following string:

[a] [abc] test [zzzz]

I'm trying to get an array like so:

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

I've tried the following code:

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

But my console output shows:

[a]
[abc]
[zzzz]

I tried adding two non-capturing groups (?:), like so:

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

But I see the same matches, unchanged.

What's going wrong, and how can I get the array I want?

Upvotes: 3

Views: 137

Answers (2)

Ro Yo Mi
Ro Yo Mi

Reputation: 15010

Regex

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

Group 1 will contain an array of strings of all the text between your open and close brackets

Example with regex only solution

Match will pull out all the matching substrings and display them, since this uses only regex it'll run slightly faster then using slice

  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
        )

)

Upvotes: 0

elclanrs
elclanrs

Reputation: 94121

match doesn't capture groups in global matches. I made a little helper for this very purpose.

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;
};

And use it like:

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

Upvotes: 3

Related Questions