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 ?
.execis stateful when you use thegflag. The state is kept in the regex object’s.lastIndexproperty.The state can be resetted by setting
.lastIndexto0or byexecinga different string.re.exec("")for instance will reset the state because the state was kept for'aaa111bbb222ccc333ddd'.The same applies to
.testmethod as well, so never usegflag with a regex that is used for.testif you prefer no surprises. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec