SimplifyC++ Article
Mastering std::regex in Modern C++ (C++11 – C++23)
Mastering std::regex in Modern C++ (C++11 – C++23)
1. Why Use std::regex?
Regular expressions allow you to search, match, and manipulate strings based on patterns, not fixed characters. They are powerful for:
Validating email addresses or phone numbers
Extracting words or numbers from a document
Replacing patterns within text
Parsing logs, configuration files, and even code
2. Required Headers and Setup
3. Main Types in <regex>
| Type | Purpose |
|---|---|
std::regex | Holds the regular expression pattern |
std::smatch | Holds match results for std::string |
std::cmatch | Match results for C-style strings |
std::regex_match | Checks if the whole string matches |
std::regex_search | Finds a substring match in the string |
std::regex_replace | Replaces matched text with a new string |
4. regex_search vs regex_match
Example: regex_search (Searches for pattern anywhere in the text)
std::string text = "Call me at 555-1234";std::regex pattern(R"(\d{3}-\d{4})");
std::smatch match;if (std::regex_search(text, match, pattern)) { std::cout << "Phone found: " << match[0] << "\n";}Example: regex_match (Full string must match)
std::string input = "abc123";std::regex pattern(R"([a-z]+[0-9]+)");
if (std::regex_match(input, pattern)) { std::cout << "Valid format\n";}5. regex_replace Example
std::string html = "<b>Bold</b>";std::regex tag(R"(<.*?>)");
std::string plain = std::regex_replace(html, tag, "");std::cout << plain; // Output: Bold6. Regex Pattern Syntax (Cheat Sheet)
Character Classes
| Syntax | Description |
|---|---|
. | Any character except newline |
[abc] | Matches any one of a, b, or c |
[^abc] | Not a, b, or c |
[a-z] | Lowercase letters |
[0-9] | Digits (0 to 9) |
\w | Word character [a-zA-Z0-9_] |
\W | Non-word character |
\d | Digit (0 to 9) |
\D | Non-digit character |
\s | Whitespace (space, tab, newline) |
\S | Non-whitespace character |
Note: Use raw strings (R"(pattern)") in C++ to avoid escaping backslashes.
Quantifiers
| Syntax | Description | Example |
|---|---|---|
* | 0 or more repetitions | a* → "", a, aa |
+ | 1 or more repetitions | a+ → a, aa |
? | 0 or 1 occurrence | a? → "", a |
{n} | Exactly n times | a{3} → aaa |
{n,} | At least n times | a{2,} → aa, aaa |
{n,m} | Between n and m times | a{2,4} → aa to aaaa |
Anchors and Boundaries
| Symbol | Description |
|---|---|
^ | Start of string |
$ | End of string |
\b | Word boundary |
\B | Not a word boundary |
Grouping and Alternation
| Syntax | Description |
|---|---|
(abc) | Capturing group |
(?:abc) | Non-capturing group |
| `a | b` |
7. Real-World Examples
Validate Email
std::regex email(R"((\w+)(\.\w+)*@(\w+)\.(\w+))");std::string s = "user.name@example.com";std::smatch m;if (std::regex_match(s, m, email)) { std::cout << "Valid email!\n";}Extract All Words from a Sentence
std::string sentence = "C++ is powerful and fast";std::regex word(R"(\w+)");auto begin = std::sregex_iterator(sentence.begin(), sentence.end(), word);auto end = std::sregex_iterator();
for (auto it = begin; it != end; ++it) { std::cout << "Word: " << it->str() << "\n";}Replace URLs with Placeholder
std::string input = "Visit http://example.com now!";std::regex url(R"(http[s]?://\S+)");std::string clean = std::regex_replace(input, url, "[link]");std::cout << clean; // Output: Visit [link] now!8. Error Handling
try { std::regex broken("[A-Z"); // Missing closing ]} catch (const std::regex_error& e) { std::cerr << "Regex error: " << e.what() << '\n';}9. Using Regex Flags
std::regex pattern("hello", std::regex_constants::icase); // Case-insensitive| Flag | Description |
|---|---|
std::regex::icase | Ignore case |
std::regex::ECMAScript | Default syntax (JavaScript-like) |
std::regex::basic | POSIX basic syntax |
std::regex::extended | POSIX extended syntax |
10. Practice Tasks for Beginners
Write a regex to validate phone numbers like
+966-55-1234567Extract all IP addresses from a log file line
Build a small command-line tool that replaces banned words in a sentence
Validate hexadecimal color values like
#FF5733or#abc