I want to split std::string
by regex
.
I have found some solutions on Stackoverflow, but most of them are splitting string by single space or using external libraries like boost.
I can't use boost.
I want to split string by regex - "\\s+"
.
I am using this g++ version g++ (Debian 4.4.5-8) 4.4.5
and i can't upgrade.
You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.
No, it does not support regex.
Split(Char[]) method, except that Regex. Split splits the string at a delimiter determined by a regular expression instead of a set of characters. The string is split as many times as possible. If no delimiter is found, the return value contains one element whose value is the original input string.
regex is a pointer to a memory location where expression is matched and stored. expression is a string type. flag to specify the type of compilation.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With