您的位置:首页 > 编程语言 > C语言/C++

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

2016-09-05 13:17 447 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: