views:

80

answers:

3
<script type='text/javascript'>

var str="('apple',16),('orange',7),('banana',12)";
var pattern=/\('([^']+)',([0-9]+)\)/gi;

var reg=new RegExp(pattern);
var arr=str.match(reg);

document.write(arr);

</script>

In the above javascript, I used two pairs of brackets in the pattern to indicate the data I want to get from the string. Obviously, you can see that I want to get the string and the number for every item. I think after the match, I should get an array like this:

arr[0][0] equals to ('apple',16)
arr[0][1] equals to apple
arr[0][2] equals to 16

arr[1][0] equals to ('orange',7)
arr[1][1] equals to orange
arr[1][2] equals to 7

...and so on

but now the arr I get is simply only the full match, like this:

arr[0] equals to ('apple',16)
arr[1] equals to ('orange',7)

...and so on

Why and how I can get back an array containing the data I specified using brackets?

+1  A: 

Remove the "global" (g) directive.

Unlike with RegExp.exec(), when you call String.match with a pattern that uses the "g" flag, capture groups are not returned, only the full matches.

You could also call exec() instead on your regular expression object:

var arr=reg.exec(str);
richardtallent
After removing the global directive, the arr only contains three items, arr[0] equals to ('apple',16) and arr[1] equals to apple and arr[2] equals to 16. But other items are still missing.
bobo
Thank you so much for your information.
bobo
This is untested, but I'm guessing you would find that arr[3] would be the next whole match, arr[4] the next fruit, etc. I.e., the returned value is a flat array, not two-dimensional.
richardtallent
+1  A: 

Regarding "why", that's simply how match() works. It returns a one-dimensional array.

I would simply use str.split(",") to get the list of pairs and iterate over the results.

Amnon
Thanks a lot for your information.
bobo
+1  A: 

You'll need to iterate and collect to get the results you were expecting

var str="('apple',16),('orange',7),('banana',12)";
var pattern=/\('([^']+)',([0-9]+)\)/gi;

var reg=new RegExp(pattern);

var arr = [];
while(match = reg.exec(str)) {
  arr[arr.length] = match;
}
Mark Stewart
I see, I really didn't know it's supposed to be used like this. Thanks a lot for your reply.
bobo
The exec() method only returns one match at a time (a point I didn't make clear in my answer) until no others are found, rather than a collection like .NET's "matches" collection. So if you want an array of the base matches, you have to build it. You could also just handle each match within the while() clause rather than building arr[].
richardtallent