Find Characters with Lazy Matching. Multiple results without g flag

Tell us what’s happening:
I haven’s put a g flag in text, yet it matches all characters of myRegex. I don’t understand that.

Your code so far


let text = "titanic";
let myRegex = /t[a-z]*i/; // Change this line
let result = text.match(myRegex);

console.log(result);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching

Global matching /g means all matches, so without the /g flag it will return after first match.

A * is for all results of the previous character or expression.

1 Like

So what your regex is doing is

t      // match on character t
[a-z]* // match zero or more of characters a-z
i      // up to and including character i

It isn’t matching everything, it matches on "titani" (note, not the last “c”). The match is greedy, so it keeps going until it can’t match any more.

So

t
i // this is in group a-z
t
a
t
i // no more i characters after this, so match ends

Compare with

/t[a-z]*?i/

The question mark there will stop it being greedy, so instead of matching "titani", it will match "ti" (there are zero characters between “t” and the first “i”), which is what I think you expected.

1 Like

Even c is included in [a-z]
.
Why is it not included ?

You’re only saying match until you reach the [specific] character i

1 Like

But we find “i” character right at first match. Why didn’t it stop at first match as it itself is “i”

This is going around in circles a bit but:

You match a sequence of characters starting with t, then possibly some a-z, then ending in i

1 Like

Does that mean that it will keep matching until last “I” that it finds in string. Or will it stop right at first “I” found ?

Right, this is really going round in circles:

Yes, it will keep.matching because it is greedy. To stop it being a greedy match, the ? is used.

1 Like

Okk, I got that lol. Was just a bit confused. No more circles.

Thanks for helping and going in circle 3 times…:grinning:

1 Like