Regex Simplified: Greedy vs. Non-Greedy Quantifiers Unraveled | Python in Tamil

Опубликовано: 21 Март 2026
на канале: Surendar Manoj
304
6

Regular expressions (regex) can be used to match and manipulate text patterns. Greedy and non-greedy (also known as lazy) quantifiers are modifiers in regex that control how many times a particular character, group, or pattern is matched.

1. Greedy Quantifiers:
Greedy quantifiers try to match as much of the input string as possible while still allowing the overall pattern to match. The most commonly used greedy quantifiers are:
`*` (asterisk): Matches zero or more occurrences of the preceding element. It will match as many occurrences as possible.
`+` (plus): Matches one or more occurrences of the preceding element. It will match as many occurrences as possible.
`?` (question mark): Matches zero or one occurrence of the preceding element. It will match as many occurrences as possible.

For example, let's consider the regex pattern `a.*b` applied to the string "abcabcabc". The `.*` part is a greedy quantifier, so it will match as many characters as possible. In this case, it will match the entire string "abcabcabc" because it satisfies the pattern by starting with "a" and ending with "b".

2. Non-Greedy (Lazy) Quantifiers:
Non-greedy quantifiers, on the other hand, try to match as little as possible while still allowing the overall pattern to match. They are denoted by adding a `?` after the quantifier symbols `*`, `+`, or `?`. The most commonly used non-greedy quantifiers are:
`*?` (asterisk followed by a question mark): Matches zero or more occurrences of the preceding element, but as few as possible.
`+?` (plus followed by a question mark): Matches one or more occurrences of the preceding element, but as few as possible.
`??` (question mark followed by a question mark): Matches zero or one occurrence of the preceding element, but as few as possible.

Using the same example as above, if we modify the regex pattern to `a.*?b` and apply it to the string "abcabcabc", the `.*?` part is a non-greedy quantifier. It will match as few characters as possible to satisfy the pattern. In this case, it will match only the substring "ab" because that is the shortest sequence starting with "a" and ending with "b" in the input string.

In summary, greedy quantifiers try to match as much as possible, while non-greedy quantifiers try to match as little as possible. The addition of a `?` after a quantifier changes it from being greedy to non-greedy.