In C++, quantifiers are special symbols that are used in regular expressions to specify the number of times a character, group of characters, or pattern should occur. There are several quantifiers available in C++, including the following:
*
: The*
quantifier specifies that the preceding character, group of characters, or pattern should occur zero or more times. For example,a*
matches zero or morea
characters.+
: The+
quantifier specifies that the preceding character, group of characters, or pattern should occur one or more times. For example,a+
matches one or morea
characters.?
: The?
quantifier specifies that the preceding character, group of characters, or pattern should occur zero or one time. For example,a?
matches zero or onea
characters.{n}
: The{n}
quantifier specifies that the preceding character, group of characters, or pattern should occur exactlyn
times. For example,a{3}
matches exactly threea
characters.{n,}
: The{n,}
quantifier specifies that the preceding character, group of characters, or pattern should occur at leastn
times. For example,a{3,}
matches at least threea
characters.{n,m}
: The{n,m}
quantifier specifies that the preceding character, group of characters, or pattern should occur at leastn
times, but no more thanm
times. For example,a{3,5}
matches at least threea
characters, but no more than fivea
characters.
Here is an example of how to use quantifiers in a regular expression in C++:
#include <iostream>
#include <regex>
int main()
{
std::string s = "aaaabbbbccccdddd";
std::regex r("a*b+c{2,4}d{2}");
if (std::regex_match(s, r))
{
std::cout << "Match found!" << std::endl;
}
else
{
std::cout << "Match not found." << std::endl;
}
return 0;
}
In this example, the regular expression a*b+c{2,4}d{2}
uses all of the quantifiers listed above. It matches a string that contains zero or more a
characters, one or more b
characters, two to four c
characters, and exactly two d
characters. In this case, the string "aaaabbbbccccdddd"
matches the regular expression, so the output is “Match found!”.