c++ 正则表达式怎么用 c++ regex库匹配实例

C++中使用正则需包含头文件,自C++11起支持std::regex库,可用于模式匹配、搜索和替换;例如用std::regex_match验证邮箱格式合法性。

在C++中使用正则表达式需要包含 头文件。C++11起引入了std::regex库,支持模式匹配、搜索、替换等操作。下面通过几个常见实例说明如何使用。

1. 匹配邮箱地址

判断一个字符串是否为合法邮箱格式:

#include 
#include 
#include 

int main() {
    std::string email = "test@example.com";
    std::regex pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");

    if (std::regex_match(email, pattern)) {
        std::cout << "邮箱格式正确\n";
    } else {
        std::cout << "邮箱格式错误\n";
    }
    return 0;
}

说明regex_match要求整个字符串完全匹配模式。R"(...)" 是原始字符串字面量,避免转义字符问题。

2. 查找字符串中的数字

从文本中找出所有连续的数字:

#include 
#include 
#include 

int main() {
    std::string text = "年龄:25,工号:10086,工资:15000";
    std::regex pattern(R"(\d+)");
    std::smatch matches;

    std::string::const_iterator start = text.begin();
    std::string::const_iterator end = text.end();

    while (std::regex_search(start, end, matches, pattern)) {
        std::cout << "找到数字: " << matches[0] << "\n";
        start = matches.suffix().first; // 移动到本次匹配结束位置
    }
    return 0;
}

说明regex_search用于在字符串中查找子串匹配,配合迭代可找出所有匹配项。matches[0]表示完整匹配结果。

3. 字符串替换(去除多余空格)

将多个连续空格替换为单个空格:

#include 
#include 
#include 

int main() {
    std::string str = "hello    world     C++";
    std::regex pattern(R"( +)");
    std::string result = std::regex_replace(str, pattern, " ");
    std::cout << "处理后: " << result << "\n"; // 输出: hello world C++
    return 0;
}

说明regex_replace返回替换后的副本,原字符串不变。模式 + 匹配一个或多个空格。

4. 提取日期中的年月日

从格式化的日期字符串中提取各部分:

#include 
#include 
#include 

int main() {
    std::string date = "2025-04-05";
    std::regex pattern(R"((\d{4})-(\d{2})-(\d{2}))");
    std::smatch match;

    if (std::regex_match(date, match, pattern)) {
        std::cout << "年: " << match[1] << "\n";
        std::cout << "月: " << match[2] << "\n";
        std::cout << "日: " << match[3] << "\n";
    }
    return 0;
}

说明:括号表示捕获组,可通过match[1]match[2]等访问对应子匹配内容。

基本上就这些常用操作。掌握regex_matchregex_searchregex_replace三个核心函数,再结合常用正则语法,就能应对大多数文本处理需求。