简体   繁体   中英

RegExp capturing group in capturing group

I want to capture the "1" and "2" in " http://test.com/1/2 ". Here is my regexp /(?:\\/([0-9]+))/g . The problem is that I only get ["/1", "/2"] . According to http://regex101.com/r/uC2bW5 I have to get "1" and "1".

I'm running my RegExp in JS.

You have a couple of options:

  1. Use a while loop over RegExp.prototype.exec :

     var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; while (match = regex.exec(string)) { matches.push(match[1]); } 
  2. Use replace as suggested by elclanrs :

     var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; string.replace(regex, function() { matches.push(arguments[1]); }); 

In Javascript your "match" has always an element with index 0 , that contains the WHOLE pattern match. So in your case, this index 0 is /1 and /2 for the second match.

If you want to get your DEFINED first Matchgroup (the one that does not include the / ), you'll find it inside the Match-Array Entry with index 1 .

This index 0 cannot be removed and has nothing to do with the outer matching group you defined as non-matching by using ?:

Imagine Javascript wrapps your whole regex into an additional set of brackets.

Ie the String Hello World and the Regex /Hell(o) World/ will result in :

[0 => Hello World, 1 => o]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM