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.
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 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.
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
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.
An introduction to regular expression capture groups, and how to use them in C++ with regex search
, replace
, iterator
, and token_iterator