In order to verify that a string matches a regular expression, perform the following steps:
- 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 most e-mails formats:
auto pattern {R"(^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$)"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 ignore casing or specify other parsing options, use an overloaded constructor that has an extra parameter for regular expression flags:
auto rx = std::regex{pattern, std::regex_constants::icase};
- Use std::regex_match() to match the regular expression to an entire string:
auto valid = std::regex_match("[email protected]"s, rx);