C++11 | 正则表达式(4)

C++11还支持正则表达式里的子表达式(也叫分组),用sub_match这个类就行了。

举个简单的例子,比如有个字符串“/id:12345/ts:987697413/user:678254”,你想提取id,就可以使用子表达式。代码片段如下:

    std::string strEx = "info=/id:12345/ts:987697413/user:678254";
    std::regex idRegex("id:(\\d+)/");
    auto itBegin = std::sregex_iterator(strEx.begin(),
                                            strEx.end(), idRegex);
    auto itEnd = std::sregex_iterator();
    std::smatch match = *itBegin;
    std::cout << "match.length : " << match.length() << "\n";
    std::cout << "entire match - " << match[0].str().c_str() << " submatch - " << match[1].str().c_str() << "\n";

在上面的代码里,smatch其实是std::match_results<std::string::const_iterator>,它代表了针对string类型的match_results,它里面保存了所有匹配到正则表达式的子串(类型为sub_match),其中索引为0的,是完整匹配到正则表达式的子串,其它的,是匹配到的子表达式的字符串结果。

对我们的代码片段,子表达式(\\d+)匹配到的数字就是12345


相关:

posted on 2016-09-05 13:17  疯子123  阅读(183)  评论(0编辑  收藏  举报

导航