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:


(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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Valid phone number
Invalid phone number

Run result:

TEXT 📖 Display only
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

Example: Finding an email (Difficulty ⭐⭐)

CPP
#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 ⭐⭐)

CPP
#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:

TEXT 📖 Display only
After hiding:138****5678


(1) 4.1 regex_iterator

Example: Find all email addresses (Difficulty ⭐⭐⭐)

CPP
#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:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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:

TEXT 📖 Display only
Year: 2026
Month: 06
Day: 28


6. Common Use Cases

(1) 6.1 Input Validation

Scenario Regular Expression
Email [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 ⭐⭐⭐)

CPP
#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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
 -> Effective
 -> Invalid

❓ FAQ

Q What if regular expressions are too slow?
A - Compile once, use multiple times (the std::regex constructor is slow) - Use the std::regex_constants::optimize flag

Q: What if there are too many escape characters? A: Use raw string literals (C++11):

CPP
// Hard to read
std::regex pattern("\\\\d+");

// Easy to read
std::regex pattern(R"(\d+)");

Q Can regular expressions handle all text?
A No. Parsing HTML/XML with regex is very complex — use a dedicated parser instead.

📖 Summary

Key Point Summary
regex_match Full match
regex_search Search
regex_replace Replace
regex_iterator Iterative search
Grouping Use () to extract substrings

📝 Exercises

  1. Basic (Difficulty ⭐): Use std::regex to check if a string matches a "pure digits" pattern (^\d+$), testing "123", "12a3", "abc".

  2. Intermediate (Difficulty ⭐⭐): Use regex_search to extract all email addresses from a text (matching the \w+@\w+\.\w+ pattern).

  3. Challenge (Difficulty ⭐⭐⭐): Use regex_replace to implement a "sensitive word filter" function — replacing specified sensitive words in text with ***. Support multiple sensitive words.



Next lesson: Multithreading Basics (#43)

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏