AI Workshop: learn to build apps with AI →
Regular Expressions: Greediness

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Regular expressions are said to be greedy by default.

What does it mean?

Take this regex

/\$(.+)\s?/

It is supposed to extract a dollar amount from a string

/\$(.+)\s?/.exec('This costs $100')[1]
//100

but if we have more words after the number, it captures too much

/\$(.+)\s?/.exec('This costs $100 and it is less than $200')[1]
//100 and it is less than $200

Why? Because the regex after the $ sign matches any character with .+, and it won’t stop until it reaches the end of the string. Then, it finishes off because \s? makes the ending space optional.

To fix this, we need to tell the regex to be lazy, and perform the least amount of matching possible. We can do so using the ? symbol after the quantifier:

/\$(.+?)\s/.exec('This costs $100 and it is less than $200')[1]
//100

I removed the ? after \s; otherwise it would match only the first number, since the space was optional.

So, ? means different things based on its position, because it can be both a quantifier and a lazy mode indicator.

Lessons in this unit:

0: Introduction
1: Introduction
2: Anchoring
3: Match Items in Ranges
4: Matching a Range Item Multiple Times
5: Negating a Pattern
6: Meta Characters
7: Regular Expressions Choices
8: Quantifiers
9: Optional Items
10: Groups
11: Capturing Groups
12: Using match and exec Without Groups
13: Noncapturing Groups
14: Flags
15: Inspecting a Regex
16: Escaping
17: String Boundaries
18: Replacing
19: ▶︎ Greediness
20: Lookaheads
21: Lookbehinds
22: Unicode
23: Unicode Property Escapes
24: Examples