c++ 正则匹配得使用

标头:#include <regex>
相关函数:
regex_match
regex_replace
regex_search

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

1. regex_search

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

//形如"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 查找多个匹配(注意:能否匹配出多个子串,与正则有关)。

	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;
	}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值