How to split a string using a regular expression delimiter in C++

1 Answer

0 votes
#include <iostream>
#include <regex>
#include <string>
#include <vector>

/*
    split_regex(s, pattern)
    -----------------------
    Splits a string using a regular expression pattern.

    This uses:
      - std::regex
      - std::sregex_token_iterator with submatch index -1
        which returns the text *between* regex matches.

    Example:
        pattern = ",+"
        "a,,b,c" → ["a", "b", "c"]
*/
std::vector<std::string> split_regex(const std::string& s, const std::string& pattern) {
    std::regex re(pattern);
    std::sregex_token_iterator it(s.begin(), s.end(), re, -1);
    std::sregex_token_iterator end;

    return {it, end};
}

int main() {
    std::string input = "Just-when--I--thought--I-was--out,-----They----pull-me-back-in.";
    std::string pattern = "-+"; // The regex pattern -+ means one or more hyphen

    auto parts = split_regex(input, pattern);

    std::cout << "\nSplit result:\n";
    for (const auto& p : parts) {
        std::cout << "[" << p << "]\n";
    }
}


/*
run:

Split result:
[Just]
[when]
[I]
[thought]
[I]
[was]
[out,]
[They]
[pull]
[me]
[back]
[in.]

*/

 



answered Jul 19 by avibootz

Related questions

1 answer 334 views
3 answers 457 views
1 answer 293 views
1 answer 268 views
1 answer 170 views
...