开发者

Rubular versus javascript regexp capture groups

开发者 https://www.devze.com 2023-04-07 09:09 出处:网络
Noticed a difference between what Rubular.com and Javascript regexes: \'catdogdogcatdog\'.match(/cat(dog)/g);// JS returns [\'catdog\', \'catdog\']

Noticed a difference between what Rubular.com and Javascript regexes:

'catdogdogcatdog'.match(/cat(dog)/g);  // JS returns ['catdog', 'catdog']  

I expected to captu开发者_如何学JAVAre 'dog' twice but instead I get 'catdog' twice.

Rubular captures 'dog' twice as expected: http://rubular.com/r/o7NkBnNs63

What is going on here exactly?


No, Rubular also matches catdog twice. It also shows you the contents of the capturing group, which captured dog twice.

Rubular versus javascript regexp capture groups

You want something like this:

var myregexp = /cat(dog)/g;
var match = myregexp.exec(subject);
while (match != null) {
    dog = match[1]
    // do something, Gromit!
    match = myregexp.exec(subject);
}
0

精彩评论

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