首页 > 后端开发 > C++ > 正文

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

裘德小鎮的故事
发布: 2025-12-13 11:24:02
原创
470人浏览过
C++中使用正则需包含头文件,自C++11起支持std::regex库,可用于模式匹配、搜索和替换;例如用std::regex_match验证邮箱格式合法性。

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

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

1. 匹配邮箱地址

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

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

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. 查找字符串中的数字

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

立即学习C++免费学习笔记(深入)”;

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

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]表示完整匹配结果。

神笔马良
神笔马良

神笔马良 - AI让剧本一键成片。

神笔马良 320
查看详情 神笔马良

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

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

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

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 <iostream>
#include <string>
#include <regex>

int main() {
    std::string date = "2024-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三个核心函数,再结合常用正则语法,就能应对大多数文本处理需求。

以上就是c++++ 正则表达式怎么用 c++ regex库匹配实例的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号