Beginner Level

Intermediate Level

Advanced Level

## Introduction

Non-greedy quantifiers are an important aspect of regular expressions, which control the behavior of matches for repeated patterns. In this tutorial, we will introduce the concept of non-greedy quantifiers in regular expressions, explain how they work, and demonstrate how to use them in Python. By the end of this tutorial, you will have a clear understanding of non-greedy quantifiers and how they can be applied in your own Python scripts.

## Regex Non-Greedy (or Lazy) Quantifiers :

- Normally, by default, regular expressions in Python try to match the longest substring possible.
- However, there are situations where you might want to use a non-greedy or lazy quantifier to match the shortest possible substring instead.
- To use non-greedy quantifiers, add a
`?`

to the end of the regular expression quantifier. - Non-Greedy quantifiers try to match the shortest possible substring that satisfies the regular expression pattern.
- Python Regex Non-Greedy Quantifiers Example
**Code Sample :**

```
import re
text = "fruit:apple, fruit:banana, fruit:cherry"
pattern = r"fruit:(.*?),"
result = re.findall(pattern, text)
print(result)
```

**Explanation :**- In the above example, the regular expression is seeking to match for all fruit and extract each as a group.
- The
`.*?`

non-greedy quantifier means it will match the shortest substring possible that satisfies the expression pattern which is "apple" in the above example. - After finding a match, the regular expression proceeds to the next comma and looks for the next possible match.
- The function
`re.findall()`

searches the whole string and returns the list of matches in this case, which is`["apple", "banana", "cherry"]`

.

Prev. Tutorial : Greedy Quantifiers

Next Tutorial : Sets & Ranges