Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only captured groups in a JavaScript RegEx with multiple matches

Simplified example:

/not(?:this|that)(.*?)end/ig.exec('notthis123end notthat45end')

returns

["notthis123end", "123"]

I'm shooting for

["123", "45"]

All I've figured out is putting the RE in a RegExp object and running a while loop around the exec, which seems kinda silly, or using match, but getting back the entire match, not just the captured part.

like image 530
swider Avatar asked Mar 22 '14 18:03

swider


1 Answers

Your RegEx seems to be working fine. Problem is with the interpretation of the output.

  1. To get multiple matches of the RegEx, you should do, something like this

    var regEx = /not(?:this|that)(.*?)end/ig;
    var data  = "notthis123end notthat45end";
    var match = regEx.exec(data);
    
    while(match !== null) {
        console.log(match[1]);
        match = regEx.exec(data);
    }
    

    Note: It is important to store the RegEx in a variable like this and use a loop with that. Because, to get the multiple matches, JavaScript RegEx implementation, stores the current index of the match in the RegEx object itself. So, next time exec is called it picks up from where it left of. If we use RegEx literal as it is, then we ll end up in infinite loop, as it will start from the beginning always.

  2. The result of exec method has to be interpreted like this, the first value is the entire match and the next element onwards we get the groups inside the matches. In this RegEx, we have only one group. So, we access that with match[1].

like image 66
thefourtheye Avatar answered Nov 20 '22 08:11

thefourtheye