下面是一个示例的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"分割成多个部分,并将结果打印出来。

注意:在使用正则表达式时,可能需要对反斜杠进行转义,例如要匹配一个句点,可以使用"\."作为正则表达式模式

写一个按照制定正则表达式分割字符串的C++函数

原文地址: https://www.cveoy.top/t/topic/h97D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录