sregex_token_iterator的使用方法
时间: 2023-12-30 19:04:32 浏览: 760
sregex_token_iterator是C++标准库的regex头文件中的一个类,它用于在字符串中搜索正则表达式,并返回一个迭代器,可以通过这个迭代器逐个访问匹配到的字符串。
使用sregex_token_iterator的步骤如下:
1. 引入regex头文件。
```C++
#include <regex>
```
2. 定义一个正则表达式对象和一个sregex_token_iterator对象。
```C++
std::regex reg("正则表达式");
std::sregex_token_iterator it(str.begin(), str.end(), reg, -1);
```
其中,str是要搜索的字符串,-1表示返回字符串中所有匹配的子串。
3. 通过循环逐个访问匹配到的字符串。
```C++
while (it != std::sregex_token_iterator()) {
std::string match = *it++;
// 处理匹配到的字符串
}
```
完整示例代码:
```C++
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "hello,world!this is a test.";
std::regex reg("[^\\w]+");
std::sregex_token_iterator it(str.begin(), str.end(), reg, -1);
while (it != std::sregex_token_iterator()) {
std::string match = *it++;
std::cout << match << std::endl;
}
return 0;
}
```
输出结果:
```
hello
world
this
is
a
test
```
阅读全文
相关推荐














