在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)中可能需要額外的支持庫。在使用時,請確保已經安裝了相應的庫。