c++正则表达式

头文件

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值