Lazy Nature
Learn about the lazy nature of RegEx.
Overview of lazy nature
You are familiar with greedy nature now. While sometimes we’ll need greedy Regex it may not be necessary. Consider the text (‘firstname’ ‘lastname’ ‘address’). Modify it a bit by removing space after “firstname” and before “lastname”. The modified text will be ‘firstname’‘lastname’ ‘address’. We will work on the same text discussed in the last lesson and derive its solution as well.
RegEx has one special character to handle its greedy nature. You have a global flag to control the eagerness of the RegEx. Similarly, the lazy character handles the greedy nature of RegEx.
Lazy characters
Lazy character is denoted by ?
. You have already been familiarized with this character in the repetition character section. You may have noticed that the same character might have several meanings depending on the context.
Lazy nature is the exact opposite of greedy nature. It tries to match as few characters as possible. When the character ?
is added, it tells the RegEx engine to avoid matching as much as possible and pass the control to the next part as soon as possible. Similarly, greedy nature continues to match until the next part of the phrase is given control. Lazy nature will attempt to give up as soon as the next part of the expression matches something.
Lazy character is denoted by ?
. You are already familiar with this character in the repetition character. You may have noticed that the same character might have several ...