How to do it...

In order to search for occurrences of a regular expression through a string you should perform the following:

  1. 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;
  1. 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};
  1. 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};
  1. 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;
}
  1. 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;
}
  1. 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;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset