Regex Capture Groups

Greedy vs Lazy Quantifiers

What are the differences between greedy and lazy quantifiers in regex?

Abstract art representing computer programming

Greedy and lazy quantifiers control how much of the input string is matched by the quantifiers in a regex pattern.

Greedy Quantifiers

Greedy quantifiers match as much of the input string as possible. By default, the quantifiers *, +, and {n,m} are greedy. This means they try to match the longest possible substring that fits the pattern.

For example:

#include <iostream>
#include <regex>

int main() {
  std::string input = "abc123def456";
  std::regex pattern(".*\\d");
  std::smatch match;
  std::regex_search(input, match, pattern);
  std::cout << match.str();
}
abc123def456

In this example, .*\d matches the entire string because .* is greedy and matches as many characters as possible before the final digit.

Lazy Quantifiers

Lazy quantifiers match as little of the input string as possible. To make a quantifier lazy, you append a ? to it. The lazy versions are *?, +?, and {n,m}?.

For example:

#include <iostream>
#include <regex>

int main() {
  std::string input = "abc123def456";
  std::regex pattern(".*?\\d");
  std::smatch match;
  std::regex_search(input, match, pattern);
  std::cout << match.str();
}
abc1

Here, .*?\d matches only abc1 because .*? is lazy and stops matching as soon as it finds a digit.

When to Use Each

Use greedy quantifiers when you want to match the longest possible substring and lazy quantifiers when you want the shortest match.

Understanding the difference helps in fine-tuning regex patterns for specific use cases, such as extracting or replacing substrings within larger text.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved