Reputation: 20806
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
Reputation: 15010
[[]\s*(\b[^]]*\b)\s*[\]]
Group 1 will contain an array of strings of all the text between your open and close brackets
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
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