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*
,你会得到不一样的结果。