Question

I'm trying to convert a string like "ABC10DEF20" to an array ["ABC", 10, "DEF", 20] using Boost Spirit. I'm not sure if "undelimited" is the right term but I want to break it up by the boundaries of integers and non-integers rather than splitting it by whitespace or another delimiting character.

I've come up with code like:

std::string search_str = "ABC10DEF20";
std::vector<boost::variant<std::string, unsigned int> > v;
std::string::const_iterator iter = search_str.begin();
std::string::const_iterator last = search_str.end();

bool r = parse(iter, last,
               +(+(char_ - digit)|uint_),
               v);

For the input "ABC10DEF20" this results in [ 65, 66, 67, 10, 68, 69, 70, 20 ] (no strings, just the integers and ASCII components of the string portion stored in integers). For the input "10" I get [ 10 ] as intended.

Was it helpful?

Solution

From the output, it's apparent you're matching individual characters, not strings, and full unsigned integers.

Not sure it'll fix it, but try:

bool r = parse(iter, last,
               +(+(+char_ - digit)|uint_),
               v);

(Note the added + before char_.)

The type of v might need to change to be: std::vector<boost::variant<std::vector<char>, unsigned int> > v;, and you might have to fixup the result. Not terribly familiar with Boost Spirit; I bet there's a better, cleaner, way.

Final Solution:

Modify the parse expression to use:

+(as_string[+(char_ - digit)]|uint_)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top