C++11 正则表达式

本文详细介绍了如何使用C++11中的正则表达式进行字符串匹配与替换,包括验证整个字符串、查找子串及替换操作的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++11 正则表达式

1、验证整个字符串是否符合给定正则表达式

2、在字符串中查找符合给定正则表达式的子串

3、在字符串中查找符合正则表达式的子串,并替换

上述三点分别对应C++11中的三个函数,包含头文件#include <regex>

验证整个字符串是否符合给定正则表达式

使用函数std::regex_match(),一般都是分三步:

1、定义正则表达式 std::regex 类,将正则表达式的字符串形式传入其构造函数进行实例化;

2、定义std::smatch matchResult用来存放匹配结果,对应正则表达式中的括号,一般一个括号为一个子表达式,可以作为参数传入函数第3步的函数,也可以不传,省略;

3、调用std::regex_match()函数,匹配成功返回true。

调用std::regex_match()函数,匹配成功返回true。 

//定义正则表达式,下面iStr为string类型
    std::regex reg("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
    std::smatch matchResult;//存放匹配成功时正则表达式中各个子表达式对应的实际字符串,下标为0是整个正则表达式对应的字符串
    //以枚举形式重载的函数
    if (std::regex_match((string::const_iterator)iStr.begin(), (string::const_iterator)iStr.end(), matchResult, reg))
    {    	
	return true;
    }
  //另一个重载函数
if (std::regex_match(iStr, matchResult, reg))
{
    return true;
}
//regex_match()函数std::smatch类型参数可以省略,例如,但此参数在循环调用regex_search()函数时十分
if (std::regex_match(iStr, reg))
{
    return true;
}

在字符串中查找符合给定正则表达式的子串

使用函数std::regex_match(),一般都是分三步:

1、定义正则表达式 std::regex 类,将正则表达式的字符串形式传入其构造函数进行实例化;

2、定义std::smatch matchResult用来存放匹配结果,matchResult[0]对应整个正则表达式的匹配结果,matchResult[1]对应正则表达式的第一个括号(第一个子表达式)的匹配结果,以此类推;

3、调用std::regex_match()函数,匹配成功返回true。

步骤和上述类似,只不过第3步调用函数std::regex_search(),要返回所有符合正则表达式的子串,可以在while循环中实现:

	std::regex reg("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
	string iStr = "192.168.1.1";
	std::smatch matchResult;

	string::const_iterator iterator = iStr.begin();
	string::const_iterator iteratorEnd = iStr.end();
	while (std::regex_search(iterator, iteratorEnd, matchResult, reg))
	{
		//matchResult[0] 代表的是匹配成功后整个正则表达式对应的字符串
		cout << matchResult[0] << endl;
		//返回的枚举是下一个循环要用的枚举,不要直接iterator++,这样写效率低
		iterator = matchResult[0].second;
	}

在字符串中查找符合正则表达式的子串,并替换

注意,regex_replace()函数会替换所有符合给定正则表达式的子串,例如下例输出结果为:"111111"

	std::regex reg("[A-Za-z]");
	string iStr = "abcdef";
	//std::smatch matchResult;

	string::const_iterator iterator = iStr.begin();
	string::const_iterator iteratorEnd = iStr.end();
	string result = std::regex_replace(iStr, reg, "1");
	cout << result;
详细请参考:
https://www.cnblogs.com/cmranger/p/4753668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值