C++ 使用正则表达式分割字符串函数
下面是一个示例的 C++ 函数,使用正则表达式分割字符串:
#include <iostream>
#include <regex>
#include <vector>
std::vector<std::string> splitString(const std::string& input, const std::string& regexPattern) {
std::regex regex(regexPattern);
std::sregex_token_iterator iterator(input.begin(), input.end(), regex, -1);
std::sregex_token_iterator end;
std::vector<std::string> result;
for (; iterator != end; ++iterator) {
result.push_back(*iterator);
}
return result;
}
int main() {
std::string input = "Hello,World,This,is,a,test";
std::vector<std::string> result = splitString(input, ",");
for (const auto& str : result) {
std::cout << str << std::endl;
}
return 0;
}
在这个示例中,splitString 函数接受两个参数:输入字符串和正则表达式模式。它使用 std::regex 和 std::sregex_token_iterator 来将输入字符串按照正则表达式模式分割成多个部分,并将结果存储在一个 std::vector<std::string> 中返回。
在 main 函数中,我们使用逗号作为分割符将字符串'Hello,World,This,is,a,test' 分割成多个部分,并将结果打印出来。
注意:在使用正则表达式时,可能需要对反斜杠进行转义,例如要匹配一个句点,可以使用'.' 作为正则表达式模式。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pSSA 著作权归作者所有。请勿转载和采集!