使用C++实现一个函数用所给正则表达式分割字符串
可以使用C++的正则表达式库<regex>来实现该函数。下面是一个示例代码:
#include <iostream>
#include <regex>
#include <vector>
std::vector<std::string> splitString(const std::string& input, const std::string& regexPattern) {
std::vector<std::string> result;
std::regex regex(regexPattern);
std::sregex_token_iterator iter(input.begin(), input.end(), regex, -1);
std::sregex_token_iterator end;
while (iter != end) {
result.push_back(*iter);
++iter;
}
return result;
}
int main() {
std::string input = "Hello, World! This is a test!";
std::string regexPattern = "[, ]+"; // 分割规则为逗号和空格
std::vector<std::string> result = splitString(input, regexPattern);
for (const auto& str : result) {
std::cout << str << std::endl;
}
return 0;
}
在上面的示例代码中,splitString函数接受两个参数:input为输入的字符串,regexPattern为正则表达式分割规则。该函数将使用正则表达式将输入字符串分割,并返回一个包含分割后的子字符串的向量。
在main函数中,我们使用示例字符串"Hello, World! This is a test!"作为输入,并使用正则表达式[, ]+作为分割规则,即逗号和空格。然后,我们将分割后的子字符串打印出来。
运行该程序,输出结果如下:
Hello
World!
This
is
a
test!
注意:在使用正则表达式库之前,需要确保你的编译环境支持C++11或更高版本
原文地址: https://www.cveoy.top/t/topic/ibnY 著作权归作者所有。请勿转载和采集!