头文件
#include <regex>
主要函数
std::regex
正则表达式对象,存储编译后的模式。
std::smatch
匹配结果容器,用于存储子匹配(捕获组)。
std::regex_match
检查整个字符串是否与模式完全匹配。
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::string email = "test@exaple.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 << "邮箱格式正确" << std::endl;
}
else
{
std::cout << "邮箱格式错误" << std::endl;
}
}
std::regex_search
在字符串中搜索第一个匹配的子串。
#include <iostream>
#include <regex>
#include <string>
int main(){
std::string text = "价格:99元,折扣:8.5折";
std::regex pattern(R"(\d+.?\d*)");
std::smatch result;
if(std::regex_search(text, result, pattern)){
std::cout << result.str() << std::endl;
}
// 遍历所有匹配
std::sregex_iterator it(text.begin(), text.end(), pattern);
std::sregex_iterator end;
for(; it != end; ++it)
{
std::cout << it->str() << std::endl;
}
}
std::regex_replace
替换字符串中匹配的部分。
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "敏感词1和敏感词2需要被替换";
std::regex pattern(R"(敏感词[12])"); // 匹配"敏感词1"或"敏感词2"
std::string replaced = std::regex_replace(text, pattern, "***");
std::cout << replaced << std::endl; // 输出 "***和***需要被替换"
return 0;
}