

So the difference between the greedy and the non-greedy match is the following: The greedy match will try to match as many repetitions of the quantified pattern as possible. For example, both substrings 'a' and 'aaa' are valid matches when matching the pattern 'a*' in the string 'aaaa'. the asterisk operator) that allows the regex engine to match the pattern multiple times.Ī given string may match the regex in multiple ways. Let’s summarize what you’ve learned so far: Greedy vs Non-Greedy Match – What’s the Difference? In this case, the regex engine matches only one character 'a', consumes it, and moves on with the next match. Second, you use the non-greedy one-or-more version 'a+?'. It’s greedy so it matches as many 'a' characters as it can (but at least one).
#Notepad++ regex not greedy plus#
Let’s start with the plus (one-or-more operator): > re.findall('a+', 'aaaa')įirst, you use the one-or-more plus regex 'a+'.

Only if it has already matched zero characters at a certain position, it matches one character at that position, “consumes” it, and moves on. Second, you use the non-greedy zero-or-one version 'a*?'. It’s greedy so it matches as many 'a' characters as it can. Let’s start with the asterisk (zero-or-more operator): > re.findall('a*', 'aaaa')įirst, you use the zero-or-more asterisk regex 'a*'. This pattern of first matching the empty string and only then matching the 'a' if it is absolutely needed repeats.
#Notepad++ regex not greedy free#
But after that, it’s free to match the empty string again. Only then, it cannot match the empty string anymore so it is forced to match the first 'a' character. Note that it moves from left to right so it matches the empty string and “consumes” it. In the second instance, you use the non-greedy zero-or-one version 'a?'.

It’s greedy so it matches one 'a' character if possible. In the first instance, you use the zero-or-one regex 'a?'. Let’s start with the question mark (zero-or-one operator): > import re Here are some examples that show how non-greedy matching works: Non-Greedy Question Mark Operator (?) they “consume” or match as few characters as possible so that the regex pattern is still satisfied. If you’re a busy person, here’s the short version of this tutorial:Ī greedy quantifier such as ?, *, +, and ?.
