Back
Close

Modern C++ idoms and recipes

meshell
9,903 views

Regular expressions

C++11 provides support for regular expressions within the standard library in the header regex through a set of classes, iterators, and algorithms. Regular expressions are used to perform pattern matching within strings.

Example

The following example checks if an input string represents a valid email address.

#include <regex>
#include <string>
#include <iostream>
using namespace std::string_literals;
bool is_valid_email(const std::string& email) {
auto pattern = R"(^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$)"s;
auto rx = std::regex{pattern, std::regex_constants::icase};
return std::regex_match(email, rx);
};
int main() {
auto test_email = [](const std::string& email) {
std::cout << email
<< " : is "
<< (is_valid_email(email) ? "valid." : "not valid")
<< "\n";
};
test_email("hans.muster@gmail.com"s);
test_email("HANS.Muster@gmail.com"s);
test_email("HANS.Muster@gmail.co.uk"s);
test_email("Hans@Muster@gmail.c"s);
test_email("HANS.Muster@gmail"s);
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

DIY

The example above verified a string by checking for a regex match. However the regex library allows also to search for matches and replace certain patterns. Try to solve the next exercise by using the right classes and algorithms from <regex> .

Implement the function according the documentation
#ifndef MODERN_CPP_REGEX_REPLACE_H
#define MODERN_CPP_REGEX_REPLACE_H
#include <string>
#include <regex>
namespace modern_cpp {
/**
* Replaces all words in 'input' containing exactly one vovel with the same word,
* but all non-vovels are replaced by *, e.g.
* "Lorem ipsum dolor sit amet" becomes "Lorem ipsum dolor *i* amet"
* @param input text to "censor"
* @return censored text
*/
std::string replace_words_with_one_vovel(const std::string& input) {
return {};
};
}
#endif //MODERN_CPP_REGEX_REPLACE_H
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants