sophisticated problem

hi,

I came across with sophisticated problem.

I need to build pattern to string that built like this "1-2,3,4-5,6-7,8-11,12..."

Namely, collection of ranges that seperated with comma (,)
every range can be displayed by two varied numbers or by single number (range in size 1).

Note that range in size 1 display like this: 3 - not like this: 3-3.

I want to use in tr1::regex and get array string: ["1-2","3","4-5"...].

The real problem it is unlown how many ranges have (it's user input)
help me please solve this with regex.


thanks

Since you don't know how many ranges there are, you have to populate a data structure that can grow as needed, not an array. I'll use a vector of strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <iostream>
#include <vector>
#include <regex>

int main()
{
    std::string in = "1-2,3,4-5,6-7,8-11,12,100-123";
    std::regex re("(\\d+(-\\d+)?),?");

    std::vector<std::string> out( std::sregex_token_iterator(in.begin(), in.end(), re, 1),
                                  std::sregex_token_iterator() );
    for(auto& s: out)
        std::cout << "\"" << s << "\"\n";
}


Tested with Visual Studio 2012 and Clang++ 3.1/libc++-svn.

If you #include <boost/regex.hpp> and use boost::regex/boost::sregex_token_iterator, this will work with GCC as well.
Last edited on
Topic archived. No new replies allowed.