Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do 'lazy' and 'greedy' mean in the context of regular expressions?

What are these two terms in an understandable way?

like image 610
ajsie Avatar asked Feb 20 '10 06:02

ajsie


People also ask

What is a lazy quantifier?

The lazy mode of quantifiers is an opposite to the greedy mode. It means: “repeat minimal number of times”. We can enable it by putting a question mark '?' after the quantifier, so that it becomes *? or +? or even ?? for '?'

What is a greedy quantifier?

Greedy Quantifier (Default) Greedy quantifiers try to match the longest text that matches a given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the whole text doesn't match, remove the last character and try again, repeating the process until a match is found. Java.

How do I make a regex not greedy?

discuss just what it means to be greedy. backing up until it can match an 'ab' (this is called backtracking). To make the quantifier non-greedy you simply follow it with a '?' the first 3 characters and then the following 'ab' is matched.

Which of the following are greedy match quantifiers?

By default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible.


1 Answers

Greedy will consume as much as possible. From http://www.regular-expressions.info/repeat.html we see the example of trying to match HTML tags with <.+>. Suppose you have the following:

<em>Hello World</em> 

You may think that <.+> (. means any non newline character and + means one or more) would only match the <em> and the </em>, when in reality it will be very greedy, and go from the first < to the last >. This means it will match <em>Hello World</em> instead of what you wanted.

Making it lazy (<.+?>) will prevent this. By adding the ? after the +, we tell it to repeat as few times as possible, so the first > it comes across, is where we want to stop the matching.

I'd encourage you to download RegExr, a great tool that will help you explore Regular Expressions - I use it all the time.

like image 200
Sampson Avatar answered Oct 02 '22 15:10

Sampson