Pattern matching checks whether structured data follows a required form. Text parsing makes this practical: input may need validation or separation into meaningful parts. section 4.8
Handwritten checks can be laborious, imprecise, and difficult to maintain. A simple email validator may find separators and nonempty words while still accepting invalid characters or malformed input. section 4.8
Modern C++ provides regular expressions through the regex header. A regular expression describes allowed text, while matching is typically implemented through state transitions; the pattern is easier to revise than scattered parser conditions. section 4.8
Email validation
The handcoded version searches for an at sign and period, then checks that three words exist. The regex version expresses the intended username, domain, and top-level-domain structure in one pattern.
Listing 4.18 Handcoded email validation function (with bugs)
bool isValidEmail(const std::string& e) {
size_t pos_at = e.find('@'); #1
if (pos_at == std::string::npos) // no '@' found
return false;
if (pos_at == 0) // no first word #2
return false;
size_t pos_period = e.find('.', pos_at); #3
if (pos_period == std::string::npos) // no '.' found
return false;
if (pos_at + 1 >= pos_period) // no middle word #4
return false;
if (pos_period == e.length() - 1) // no last word #5
return false;
return true;
}
int main() {
std::cout << isValidEmail("prof@nu.edu") << '\n';
return 0;
}
Inspect the validation conditions and the gaps that make handwritten pattern matching imprecise. section 4.8
Listing 4.19 Using a regular expression for email validation
bool isValidEmail(const std::string& e) {
std::regex pattern(
R"([a-zA-Z0-9._%+-][CA}+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})"; #1
return std::regex_search(e, pattern);
}
int main() {
std::cout << isValidEmail("prof@nu.edu") << '\n';
return 0;
}
Compare the compact regular-expression implementation with the manually coordinated separator checks. section 4.8











