Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}
Enter to Rename, Shift+Enter to Preview
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content