Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Split string by regex

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.

like image 982
nothing-special-here Avatar asked May 25 '13 11:05

nothing-special-here


People also ask

Can we use regex in split a string?

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.

Does Strtok take regex?

No, it does not support regex.

How does regex split work?

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.

What is regex in C?

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.


1 Answers

#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.

like image 66
Pete Becker Avatar answered Sep 24 '22 14:09

Pete Becker