Regex Capture Groups

Non-Capture Groups

What are non-capture groups and when should they be used?

Abstract art representing computer programming

Non-capture groups in regex allow you to group parts of your pattern without saving the matched content. This can be useful for applying quantifiers or logical operations to parts of your regex without creating additional groups in the result.

Syntax

Non-capture groups are defined using (?: ...) instead of the regular capture group parentheses ( ... ). For example:

#include <iostream>
#include <regex>

int main() {
  std::string input = "apple orange banana";
  std::regex pattern("(?:apple|orange) banana");
  std::smatch match;
  std::regex_search(input, match, pattern);
  std::cout << match.str();
}
orange banana

Here, (?:apple|orange) banana matches either "apple banana" or "orange banana", but does not create a separate capture group for "apple" or "orange".

Use Case 1: To Group Without Capturing

Use non-capture groups when you need to group parts of your regex pattern without the overhead of capturing. This is useful for cleaner and more efficient regex patterns.

Use Case 2: To Apply Quantifiers

Non-capture groups are helpful when you want to apply quantifiers to a group of expressions without capturing the group:

#include <iostream>
#include <regex>

int main() {
  std::string input = "The quick brown fox";
  std::regex pattern("(?:quick|slow) brown");
  std::smatch match;
  std::regex_search(input, match, pattern);
  std::cout << match.str();
}
quick brown

Use Case 3: To Control Alternation

They are also used to control alternation (|) without capturing the alternatives:

#include <iostream>
#include <regex>

int main() {
  std::string input = "red fox";
  std::regex pattern("(?:red|blue) fox");
  std::smatch match;
  std::regex_search(input, match, pattern);
  std::cout << match.str();
}
red fox

Non-capture groups provide flexibility in crafting regex patterns that are both efficient and easy to read.

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:

  • 125 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