In order to search for occurrences of a regular expression through a string you should perform the following:
- Include headers <regex> and <string> and the namespace std::string_literals for C++14 standard user-defined literals for strings:
#include <regex>
#include <string>
using namespace std::string_literals;
- Use raw string literals to specify the regular expression to avoid escaping backslashes (that can occur frequently). The following regular expression validates the file format proposed earlier:
auto pattern {R"(^(?!#)(w+)s*=s*([wd]+[wd._,-:]*)$)"s};
- Create an std::regex/std::wregex object (depending on the character set that is used) to encapsulate the regular expression:
auto rx = std::regex{pattern};
- To search for the first occurrence of a regular expression in a given text, use the general purpose algorithm std::regex_search() (example 1):
auto match = std::smatch{};
if (std::regex_search(text, match, rx))
{
std::cout << match[1] << '=' << match[2] << std::endl;
}
- To find all the occurrences of a regular expression in a given text, use the iterator std::regex_iterator (example 2):
auto end = std::sregex_iterator{};
for (auto it=std::sregex_iterator{ std::begin(text),
std::end(text), rx };
it != end; ++it)
{
std::cout << ''' << (*it)[1] << "'='"
<< (*it)[2] << ''' << std::endl;
}
- To iterate through all the subexpressions of a match, use the iterator std::regex_token_iterator (example 3):
auto end = std::sregex_token_iterator{};
for (auto it = std::sregex_token_iterator{
std::begin(text), std::end(text), rx };
it != end; ++it)
{
std::cout << *it << std::endl;
}