c++ 正则匹配得使用

标头:#include <regex>

相关函数:

regex_match

regex_replace

regex_search

名称 描述
regex_match 测试正则表达式是否与整个目标字符串相完全匹配。
regex_replace 替换匹配正则表达式。
regex_search 搜索正则表达式匹配项。

成功搜索到其正则表达式 re 时,函数才返回 true

cpp 复制代码
//形如"2024-01-01 01-01-01" 时间匹配正则
wregex rx(L"\\d{4}(\\-|\\/|.)\\d{1,2}(\\-|\\/|.)\\d{1,2}\\s\\d{1,2}(\\-|\\/|.)\\d{1,2}(\\-|\\/|.)\\d{1,2}(\\-|\\/|.)");
wsmatch mr;
if (regex_search(recordedInfo, mr, rx))
{
    time = mr[0].str();
    std::wstring iStart(time);
    std::wsmatch result;
    std::vector<std::wstring> vTime;
    vTime.clear();
	while (regex_search(iStart, result, std::wregex(L"\\d{1,}")))
	{
        vTime.emplace_back(result[0].str());
        iStart = result.suffix();
	}
	//concatenate string
    if (vTime.size() >= 5)
    {
        std::wstring temp;
        temp.append(vTime[0]);
        temp.append(L"-");
        temp.append(vTime[1]);
        temp.append(L"-");
        temp.append(vTime[2]);
        temp.append(L" ");
        temp.append(vTime[3]);
        temp.append(L":");
        temp.append(vTime[4]);
        if (vTime.size() >= 6)
        {
			temp.append(L":");
			temp.append(vTime[5]);
        }
        time = temp;
    }
}

2. regex_match

测试正则表达式是否与整个目标字符串相完全匹配。字符串与正则表达式参数 完全匹配时才返回 true。因此,如果我们得需求是:当某字符串与指定正则完全匹配时,按照指定规则抽取数据,然后具体得业务操作。那么第一步可以使用该函数。

第二步,使用 regex_search 匹配目标序列中的子字符串,并使用 regex_iterator 查找多个匹配(注意:能否匹配出多个子串,与正则有关)。

cpp 复制代码
	std::regex rx("c(a*)|(b)");
	std::cmatch mr;
	std::regex_search("xcaaay", mr, rx);

	// index through submatches
	for (size_t n = 0; n < mr.size(); ++n)
	{
		std::cout << "submatch[" << n << "]: matched == " << mr[n].matched << ",at position " << mr.position(n) << ", " << mr.length(n) << " chars, value == " << mr[n] << std::endl;
	}
	std::cout << std::endl;

	// iterate through submatches
	for (std::cmatch::iterator it = mr.begin(); it != mr.end(); ++it)
	{
		std::cout << "next submatch: matched == " << it->matched <<", " << it->length() << " chars, value == " << *it << std::endl;
	}
相关推荐
小飞猪Jay30 分钟前
C++面试速通宝典——13
jvm·c++·面试
Kalika0-041 分钟前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch43 分钟前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家1 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技1 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web1 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的1 小时前
[C语言]--编译和链接
c语言·开发语言
rjszcb1 小时前
一文说完c++全部基础知识,IO流(二)
c++
小字节,大梦想2 小时前
【C++】二叉搜索树
数据结构·c++
吾名招财2 小时前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn