std::regex匹配正则表达式C++11

C++11中引入的这个正则表达式解析的还是挺好用的。

代码

unpack_call 的目的是将input拆分出name和value的值。

这个例子没什么用,就看看效果就好

例子:name: hello ; value: world
打印输出:
name: hello ; value: world
hello
world

#include <regex>

static bool diag_call(const std::string& input)
{
	// s 是匹配空格的, w是匹配大小写字母数字和下划线, *不解释
	// 中间被()括起来的,会在result中保存下来
	// result[0]是完整的匹配,result[1]是第一个括号中的内容
    static std::regex regex("\\s*name:\\s*(\\w*)\\s*;\\s*value:\\s*(\\w*)\\s*");
    std::smatch result;
    bool retval = false;
    if (!input.empty() && std::regex_match(input, result, regex))
    {
        for (int i = 0; i< result.size(); i++)
        {
            cout << result[i] <<endl;
        }
    }
    return true;
}

注:括号还是可以嵌套的。比如正则表达式写成\\s*name:\\s*(\\w*(\\s*));\\s*value:\\s*(\\w*)\\s*,你会得到不一样的结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值