开发者

How do we retrieve the pattern subset using regular expression in javascript?

开发者 https://www.devze.com 2022-12-11 07:33 出处:网络
<script type=\'text/javascript\'> var str=\"(\'apple\',16),(\'orange\',7),(\'banana\',12)\"; var pattern=/\\(\'([^\']+)\',([0-9]+)\\)/gi;
<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 开发者_如何学Pythonmatch, 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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消