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.
Your RegEx seems to be working fine. Problem is with the interpretation of the output.
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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With