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

在C++中使用正则表达式需要包含 std::regex库,支持模式匹配、搜索、替换等操作。下面通过几个常见实例说明如何使用。
判断一个字符串是否为合法邮箱格式:
#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"(...)" 是原始字符串字面量,避免转义字符问题。
从文本中找出所有连续的数字:
立即学习“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]表示完整匹配结果。
将多个连续空格替换为单个空格:
#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返回替换后的副本,原字符串不变。模式 + 匹配一个或多个空格。
从格式化的日期字符串中提取各部分:
#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_match、regex_search和regex_replace三个核心函数,再结合常用正则语法,就能应对大多数文本处理需求。
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号