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

来源:互联网 发布:半条命gman知乎 编辑:程序博客网 时间:2024/06/07 07:08

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


相关:

  • C++11 | 正则表达式(3)
  • C++11 | 正则表达式(2)
  • C++11 | 正则表达式(1)
  • C++11 | range-based for loop
  • C++11 | 自动类型推断——auto
  • C++11 | 运行时类型识别(RTTI)
1 0
原创粉丝点击