ZH ·
🌏 English

C++ 正则表达式入门指南

在 C++11 标准引入之前,处理正则表达式往往需要依赖 Boost 等第三方库。随着 C++11 的发布,标准库中正式加入了 <regex> 头文件,使得开发者能够直接使用标准 API 进行高效的字符串匹配、搜索与替换。

核心组件

std::regex 库主要包含以下几个核心组件:

  1. std::regex: 用于定义正则表达式对象。
  2. std::smatch: 用于存储匹配结果的容器(针对 std::string)。
  3. std::regex_match: 尝试匹配整个目标字符串。
  4. std::regex_search: 在目标字符串中搜索匹配的子串。
  5. std::regex_replace: 替换匹配到的内容。

基本使用示例

以下代码展示了如何使用 std::regex_match 来判断字符串是否符合特定格式:

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

int main() {
    std::string text = "Hello, C++11";
    std::regex pattern("Hello, C\\+\\+\\d+");

    if (std::regex_match(text, pattern)) {
        std::cout << "匹配成功!" << std::endl;
    } else {
        std::cout << "匹配失败。" << std::endl;
    }
    return 0;
}

提取匹配内容

通过 std::smatch,我们可以轻松提取正则表达式中的捕获组(Capture Groups):

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

int main() {
    std::string text = "User: Alice, ID: 12345";
    std::regex pattern("User: (\\w+), ID: (\\d+)");
    std::smatch matches;

    if (std::regex_search(text, matches, pattern)) {
        std::cout << "用户名: " << matches[1] << std::endl;
        std::cout << "ID: " << matches[2] << std::endl;
    }
    return 0;
}

注意事项

通过合理使用这些工具,C++ 开发者可以极大地简化复杂的文本解析任务。