bozhidarc
bozhidarc

Reputation: 854

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.

Upvotes: 1

Views: 86

Answers (2)

cmbuckley
cmbuckley

Reputation: 42537

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

Upvotes: 1

dognose
dognose

Reputation: 20909

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.

I.e. the String Hello World and the Regex /Hell(o) World/ will result in :

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

Upvotes: 0

Related Questions