C++: Regular Expressions
Last updated: 2026-08-26
In lesson 41, we learned about file operations.
Now, we'll learn regular expressions — the "Swiss Army knife" of text processing.
Validating emails, extracting phone numbers, replacing text... regular expressions provide a concise solution for all of these.
1. Regular Expression Overview
(1) 1.1 What Are Regular Expressions?
Regular expressions (Regex) are a text pattern description language used for matching, searching, and replacing text.
Real-life analogy:
- Wildcard
*→ matches any characters - Regular expressions → a more powerful version of wildcards
(2) 1.2 C++ Regular Expression Library
C++11 introduced regular expression support in the regex header file.
Four main functions:
| Function | Purpose |
|---|---|
std::regex_match |
Full match |
std::regex_search |
Search |
std::regex_replace |
Replace |
std::regex_iterator |
Iterative search |
2. Basic Matching
(1) 2.1 regex_match — Full Match
Example: Validating a phone number (Difficulty ⭐)
▶ Example 1: Regular expression application (Difficulty ⭐)
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string phone = "13812345678";
std::regex pattern("^1[3-9]\\d{9}$"); // Phone number regex
if (std::regex_match(phone, pattern)) {
std::cout << "Valid phone number" << std::endl;
} else {
std::cout << "Invalid phone number" << std::endl;
}
return 0;
}
Output:
Valid phone number
Invalid phone number
Run result:
Valid phone number
(2) 2.2 Regular Expression Syntax
| Symbol | Meaning | Example |
|---|---|---|
. |
Any character | a.c matches abc |
^ |
Beginning | ^abc matches strings starting with abc |
$ |
End | abc$ matches strings ending with abc |
* |
Zero or more | a* matches aaa |
+ |
One or more | a+ matches aaa |
? |
Zero or one | a? matches a or `` |
{n} |
Exactly n times | a{3} matches aaa |
[abc] |
Character set | [abc] matches a or b or c |
[^abc] |
Negated set | [^abc] matches any character except abc |
\d |
Digit | \d matches 0-9 |
\w |
Word character | \w matches a-z, A-Z, 0-9, _ |
3. Search and Replace
(1) 3.1 regex_search — Search
Example: Finding an email (Difficulty ⭐⭐)
#include <iostream>
### ▶ Example 2: Regular expression application (Difficulty ⭐)
#include <regex>
#include <string>
int main() {
std::string text = "Contact me:abc@example.com or test@gmail.com";
std::regex pattern("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
std::smatch match;
if (std::regex_search(text, match, pattern)) {
std::cout << "Found email: " << match[0] << std::endl;
}
return 0;
}
(2) 3.2 regex_replace — Replace
Example: Masking the middle four digits of a phone number (Difficulty ⭐⭐)
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string phone = "13812345678";
std::regex pattern("(\\d{3})\\d{4}(\\d{4})");
std::string result = std::regex_replace(phone, pattern, "$1****$2");
std::cout << "After hiding:" << result << std::endl;
return 0;
}
Run result:
After hiding:138****5678
4. Iterative Search
(1) 4.1 regex_iterator
Example: Find all email addresses (Difficulty ⭐⭐⭐)
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Contact me:abc@example.com or test@gmail.com";
std::regex pattern("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
auto begin = std::sregex_iterator(text.begin(), text.end(), pattern);
auto end = std::sregex_iterator();
std::cout << "Found email: " << std::endl;
for (auto it = begin; it != end; ++it) {
std::cout << it->str() << std::endl;
}
return 0;
}
Run result:
Found email:
abc@example.com
test@gmail.com
5. Grouping and Capturing
(1) 5.1 Grouping
Use parentheses () to create groups, which can extract substrings.
Example: Extracting a date (Difficulty ⭐⭐)
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string date = "2026-06-28";
std::regex pattern("(\\d{4})-(\\d{2})-(\\d{2})");
std::smatch match;
if (std::regex_match(date, match, pattern)) {
std::cout << "Year: " << match[1] << std::endl;
std::cout << "Month: " << match[2] << std::endl;
std::cout << "Day: " << match[3] << std::endl;
}
return 0;
}
Run result:
Year: 2026
Month: 06
Day: 28
6. Common Use Cases
(1) 6.1 Input Validation
| Scenario | Regular Expression |
|---|---|
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} |
|
| Phone number | ^1[3-9]\d{9}$ |
| ID card | ^\d{17}[\dXx]$ |
| IP address | ^(\d{1,3}\.){3}\d{1,3}$ |
(2) 6.2 Extracting Information
Example: Extracting links from HTML (Difficulty ⭐⭐⭐)
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string html = "<a href=\"https://example.com\">Example</a>";
std::regex pattern("<a href=\"([^\"]+)\"");
std::smatch match;
if (std::regex_search(html, match, pattern)) {
std::cout << "Link: " << match[1] << std::endl;
}
return 0;
}
▶ Example 3: Validating email format (Difficulty ⭐)
#include <iostream>
#include <regex>
#include <string>
bool isValidEmail(const std::string& email) {
std::regex pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
return std::regex_match(email, pattern);
}
int main() {
std::string emails[] = {"test@example.com", "invalid-email", "user.name@domain.org"};
for (const auto& email : emails) {
if (isValidEmail(email)) {
std::cout << email << " -> Effective" << std::endl;
} else {
std::cout << email << " -> Invalid" << std::endl;
}
}
return 0;
}
Output:
-> Effective
-> Invalid
❓ FAQ
std::regex constructor is slow) - Use the std::regex_constants::optimize flagQ: What if there are too many escape characters? A: Use raw string literals (C++11):
// Hard to read
std::regex pattern("\\\\d+");
// Easy to read
std::regex pattern(R"(\d+)");
📖 Summary
| Key Point | Summary |
|---|---|
| regex_match | Full match |
| regex_search | Search |
| regex_replace | Replace |
| regex_iterator | Iterative search |
| Grouping | Use () to extract substrings |
📝 Exercises
-
Basic (Difficulty ⭐): Use
std::regexto check if a string matches a "pure digits" pattern (^\d+$), testing "123", "12a3", "abc". -
Intermediate (Difficulty ⭐⭐): Use
regex_searchto extract all email addresses from a text (matching the\w+@\w+\.\w+pattern). -
Challenge (Difficulty ⭐⭐⭐): Use
regex_replaceto implement a "sensitive word filter" function — replacing specified sensitive words in text with***. Support multiple sensitive words.
- Regular expressions: pattern matching strings
- std::regex constructs regex objects
- std::regex_match for full matching
- std::regex_search for search matching
- std::regex_replace replaces matched content
Next lesson: Multithreading Basics (#43)