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. 查找字符串中的数字
从文本中找出所有连续的数字:
立即学习“C++免费学习笔记(深入)”;
#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 = "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_match、regex_search和regex_replace三个核心函数,再结合常用正则语法,就能应对大多数文本处理需求。
以上就是c++++ 正则表达式怎么用 c++ regex库匹配实例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488746.html
微信扫一扫
支付宝扫一扫