C++正则表达式:完整指南与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

C++ 中的正则表达式:字符串处理的强大工具

正则表达式(regex)是一种基于模式在文本中搜索和操作子字符串的形式语言。在 C++ 中,对正则表达式的支持出现在 C++11 标准中,并通过 <regex> 库实现。这是数据验证、日志解析、模式搜索和文本替换不可或缺的工具。

在本文中,我们将解析 regex 库的主要功能,学习如何编写模式,并查看实际代码示例。



1. <regex> 库的主要类型和函数

在 C++ 中,使用三个主要类来处理正则表达式:

  • std::regex — 表示正则表达式本身(模式)。
  • std::smatch — 用于存储搜索结果的容器(适用于 std::string 类型的字符串)。
  • std::cmatch — 用于 C 字符串(const char*)的类似容器。

应用正则表达式的关键函数:

  • std::regex_match() — 检查整个字符串是否与模式匹配。
  • std::regex_search() — 在字符串中搜索模式的第一个匹配项。
  • std::regex_replace() — 将所有匹配项替换为指定的文本。


#include <iostream>#include <regex>#include <string>

int main() { std::string text = "My number: +7-123-456-78-90"; std::regex pattern(R"(\\+7-\\d{3}-\\d{3}-\\d{2}-\\d{2})");

if (std::regex_search(text, pattern)) { std::cout << "Number found!" << std::endl; }

// Extract the match std::smatch match; if (std::regex_search(text, match, pattern)) { std::cout << "Found number: " << match[0] << std::endl; }

return 0;}


2. 正则表达式语法:元字符和量词

C++ 中的正则表达式模式使用类似于 ECMAScript 的语法(默认情况下)。以下是基本元素:

  • 点号 (.) — 除换行符外的任意单个字符。
  • 星号 (*) — 前一个字符的 0 次或多次重复。
  • 加号 (+) — 1 次或多次重复。
  • 问号 (?) — 0 次或 1 次重复(使字符变为可选)。
  • 方括号 ([]) — 字符类(例如,[0-9] — 任意数字)。
  • 圆括号 (()) — 分组和捕获子字符串。
  • 竖线 (|) — 逻辑 OR。
  • 脱字符 ^ — 字符串的开头。
  • 美元符号 $ — 字符串的结尾。

量词示例:

  • \\d{3} — 恰好 3 位数字。
  • \\w{2,4} — 2 到 4 个字母数字字符。
  • [A-Za-z]+ — 一个或多个拉丁字母。


#include <iostream>#include <regex>#include <string>

int main() { std::string email = "user@example.com"; // Simple pattern for email std::regex email_pattern(R"([\\w.+-]+@[\\w-]+\\.[\\w.]+)");

if (std::regex_match(email, email_pattern)) { std::cout << "Email is valid." << std::endl; } else { std::cout << "Email is invalid." << std::endl; }

// Phone number validation std::string phone = "+7 (495) 123-45-67"; std::regex phone_pattern(R"(\\+7\\s?\\(?\\d{3}\\)?\\s?\\d{3}-?\\d{2}-?\\d{2})");

if (std::regex_match(phone, phone_pattern)) { std::cout << "Phone number is valid." << std::endl; }

return 0;}


3. 使用捕获组提取数据

捕获组

博客

书籍推荐