I have made a simple code for capturing a certain group in a string :
/[a-z]+([0-9]+)[a-z]+/gi (n chars , m digts , k chars).
code :
var myString='aaa111bbb222ccc333ddd';
var myRegexp=/[a-z]+([0-9]+)[a-z]+/gi;
var match=myRegexp.exec(myString);
console.log(match)
while (match != null)
{
match = myRegexp.exec(myString);
console.log(match)
}
The result were :
["aaa111bbb", "111"]
["ccc333ddd", "333"]
null
But wait a minute ,
Why he didnt try the bbb222ccc part ?
I mean ,
It saw the aaa111bbb but then he should have try the bbb222ccc... ( That's greedy !)
What am I missing ?
Also
looking at
while (match != null)
{
match = myRegexp.exec(myString);
console.log(match)
}
how did it progressed to the second result ? at first there was :
var match=myRegexp.exec(myString);
later ( in a while loop)
match=myRegexp.exec(myString);
match=myRegexp.exec(myString);
it is the same line ... where does it remember that the first result was already shown ?
"ccc333ddd". Greedy means that+will attempt to match as much as possible without taking into account that the next part of the regex could match it.