Posts

Showing posts with the label Split

C++ - Split String By Regex

Answer : #include <regex> std::regex rgx("\\s+"); std::sregex_token_iterator iter(string_to_split.begin(), string_to_split.end(), rgx, -1); std::sregex_token_iterator end; for ( ; iter != end; ++iter) std::cout << *iter << '\n'; The -1 is the key here: when the iterator is constructed the iterator points at the text that precedes the match and after each increment the iterator points at the text that followed the previous match. If you don't have C++11, the same thing should work with TR1 or (possibly with slight modification) with Boost. To expand on the answer by @Pete Becker I provide an example of resplit function that can be used to split text using regexp: #include <regex> std::vector<std::string> resplit(const std::string & s, std::string rgx_str = "\\s+") { std::vector<std::string> elems; std::regex rgx (rgx_str); std::sregex_token_iterator iter(s.begin(...