温馨提示×

C++中如何结合正则表达式使用strtok_r

c++
小樊
99
2024-08-29 18:32:51
栏目: 编程语言

在C++中,你可以使用std::regex库来处理正则表达式,而strtok_r是一个C风格的字符串分割函数

#include<iostream> #include<string> #include<vector> #include<regex> #include <cstring> int main() { std::string input = "This is a test string"; std::regex word_regex("\\w+"); // 匹配单词 std::smatch match; std::vector<std::string> words; while (std::regex_search(input, match, word_regex)) { words.push_back(match.str()); input = match.suffix().str(); } for (const auto& word : words) { std::cout<< word<< std::endl; } return 0; } 

在这个例子中,我们使用了std::regex库来匹配单词。std::regex_search函数会在输入字符串中查找与正则表达式匹配的部分,并将匹配结果存储在std::smatch对象中。然后,我们将匹配到的单词添加到一个std::vector<std::string>容器中,并继续在剩余的字符串中查找匹配项。

注意:std::regex库在某些编译器(如GCC)中可能需要额外的支持库。在使用时,请确保已经安装了相应的库。

0