C++11 | 正则表达式(4)
2016-09-05 13:17
447 查看
C++11还支持正则表达式里的子表达式(也叫分组),用sub_match这个类就行了。
举个简单的例子,比如有个字符串“
在上面的代码里,smatch其实是
对我们的代码片段,子表达式
相关:
C++11 | 正则表达式(3)
C++11 | 正则表达式(2)
C++11 | 正则表达式(1)
C++11 | range-based for loop
C++11 | 自动类型推断——auto
C++11 | 运行时类型识别(RTTI)
举个简单的例子,比如有个字符串“
/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)
相关文章推荐
- C++生成不重复的随机数
- configure: error: C++ preprocessor "/lib/cpp" fails sanity check
- 鼠标键盘学习
- C语言(数组与指针)
- 21天习惯养成法
- C++ extern 和 static
- c/c++/c# 快速计算 Cumulative Normal Distribution 正态累积函数CDF
- C++获得当前系统所有进程
- C++11中lambda表达式
- C语言(循环结构)
- C++文件操作
- C++笔记(继承,多态,虚函数,模板函数,异常捕获)
- C语言基础学习基本数据类型-Char类型
- 【C++】输入多行数字到数组
- C语言基础学习基本数据类型-Char类型
- (15 C++ Homework) D&A 2 Array
- (15C++ for homework)Point&Line
- Set Operations(DS)(15C++)
- (15 C++ Homework) Alipay System 1 user
- (15C++ for homework)Vector-ND