C++ - 通过正则表达式拆分字符串

2021-12-28 00:00:00 string regex split c++

我想用 regex 分割 std::string.

我在 Stackoverflow 上找到了一些解决方案,但其中大部分是按单个空格拆分字符串或使用 boost 等外部库.

I have found some solutions on Stackoverflow, but most of them are splitting string by single space or using external libraries like boost.

我不能使用 boost.

I can't use boost.

我想通过正则表达式拆分字符串 - "\s+".

I want to split string by regex - "\s+".

我正在使用这个 g++ 版本 g++ (Debian 4.4.5-8) 4.4.5 但我无法升级.

I am using this g++ version g++ (Debian 4.4.5-8) 4.4.5 and i can't upgrade.

推荐答案

如果你只是想用多个空格分割一个字符串,你不需要使用正则表达式.编写自己的正则表达式库对于这么简单的事情来说太过分了.

You don't need to use regular expressions if you just want to split a string by multiple spaces. Writing your own regex library is overkill for something that simple.

您在评论中链接的答案,在 C++ 中拆分字符串?,可以轻松更改,以便在有多个空格时不包含任何空元素.

The answer you linked to in your comments, Split a string in C++?, can easily be changed so that it doesn't include any empty elements if there are multiple spaces.

std::vector<std::string> &split(const std::string &s, char delim,std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        if (item.length() > 0) {
            elems.push_back(item);  
        }
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

通过检查 item.length() >0 在将 item 推送到 elems 向量之前,如果您的输入包含多个分隔符(在您的情况下为空格),您将不再获得额外的元素

By checking that item.length() > 0 before pushing item on to the elems vector you will no longer get extra elements if your input contains multiple delimiters (spaces in your case)

相关文章