RegEx - Greedy operators

I understand the principle of greedy and lazy operators, but I don’t understand how does the global tag come into play when using a greedy operator.

In the regex section ’ Find Characters with Lazy Matching’, the regex /t[a-z]*i/ will match ‘titani’ in the string ‘titanic’. WHY? There’s no global operator to tell it to search the whole string. What if I’m just looking to find the first case that matches the pattern?

Also, the inclusion of the global operator doesn’t make the pattern find all the matches!
So for example:

                let greedyString = "titanic";
		let greedyRegex = /t[a-z]*i/g;
		let result4 = greedyString.match(greedyRegex);

The result won’t be ‘ti, titani’, as I would expect, but only ‘titani’. What’s going on here?

Much obliged,

Hi @glebusha

I think this tool will help you:

You can edit flags too clicking on the right side of the input. You will see a short explanation on right side menu.

I hope it helps, keep the good work and happy coding!

Then that’s what you tell it to do, rather than the default (greedy):


Well, no. Once it’s found a pattern, that’s that match done, that part of the string’s been consumed. Out of necessity, a regex is a very simple machine, it moves forwards through the string looking for a pattern or patterns.

Haha, yes just fat fingered it into the wrong place, edited

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.