c++ 正则表达式

20 篇文章 0 订阅

 

c++正则表达式的三部分

1)正则匹配

 

2)正则搜索

 

3)正则替换

 


 

正则搜索 案例1:
读入一个文件,从中提取第一个“key number"中的number并返回

//读入一个文件,从中提取key 0.36中的0.36并返回
float  getParamByKey(const std::string& filePath, const std::string paramName) 
{
	if (/*filtpath不存在*/) {
		std::cerr << "xxxx" << std::endl;
	}
	else 
	{
		//将文件内容读入string:
		std::ifstream ifs(filePath);
		std::string content((std::istreambuf_iterator<char>(ifs)),
			(std::istreambuf_iterator<char>()));

		std::string::const_iterator iter = content.begin();
		std::string::const_iterator iterEnd = content.end();
		std::smatch result;

		std::string regex_str1(" *" + paramName + " *[0-9]*\.[0-9]* *\n");//匹配keyName 3.66这种情况;
		std::regex pattern1(regex_str1, std::regex::icase);
		if (std::regex_search(iter, iterEnd, result, pattern1))//找到第一个匹配的字符串
		{
			std::string resStr = result[0]; //keyName 3.66
			
			std::string regex_str2("[0-9]*\.[0-9]*\n");//从keyName 3.66中提取出3.66
			std::regex pattern2(regex_str2, std::regex::icase);
			std::smatch result2;
			if (std::regex_search(resStr.cbegin(), resStr.cend(), result2, pattern2))
			{
				std::string strVal = result2[0];
				float val = atof(strVal.c_str());
				return val;
			}
		}
	}

}

 

正则搜索案例2: 从文件中找出所有的 ”keyNme 数字“ 字符串:

int main()
{
   
	//read file to string:
        std::ifstream ifs("C:/myfile.txt");
	std::string content((std::istreambuf_iterator<char>(ifs)),
		(std::istreambuf_iterator<char>()));
	
	string regex_str(" *keyName *[0-9]*\.[0-9]* *\n");
	
	regex pattern1(regex_str, regex::icase);

	string::const_iterator iter = content.begin();
	string::const_iterator iterEnd = content.end();
	string temp;
	//正则查找
	smatch result;
	while (std::regex_search(iter, iterEnd, result, pattern1)) {
		temp = result[0];
		cout << temp << endl;
		iter = result[0].second; //更新搜索起始位置
	}
}

==

Ref:

https://www.cnblogs.com/z1987/p/5191702.html

https://www.cnblogs.com/coolcpp/p/cpp-regex.html

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值