HowTo parse numbers from string with BOOST methods?
Problem: Visual C++ 10 project (using MFC and Boost libraries). In one of my methods I'm reading simple test.txt file.
Here is what inside of the file (std::string
):
12 asdf789, 54,19 1000 nsfewer:22!13
Then I need to convert all digits to in开发者_Python百科t only with boost methods. For example, I have a list of different characters which I have to parse:
( ’ ' )
( [ ], ( ), { }, ⟨ ⟩ )
( : )
( , )
( ! )
( . )
( - )
( ? )
( ‘ ’, “ ”, « » )
( ; )
( / )
And after conversation I must have some kind of a massive of int's values, like this one:
12,789,54,19,1000,22,13
Maybe some one already did this job?
PS. I'm new for boost.
Thanks!
Update
Here is my sample:
std::vector<int> v;
rule<> r = int_p[append(v)] >> *(',' >> int_p[append(v)]);
parse(data.c_str(), r, space_p);
All I have to do, is to add additional escape characters (,'[](){}:!
...) in my code, but did not find how to do that!
- Easy way out is regex.
- Hard way out is using spirit
- Middle-of-the-road is using algorithm::string::split, with the correct separators, and then looping over all individual parts using lexical_cast<>(). That way you can filter out the integers.
But again, regex will be much more robust plus it's much cleaner than all sorts of primitive string manipulation hacking.
In addition to regex, boost::spirit, and manually parsing the text, you can use AXE parser generator with VC++ 2010. The AXE rule would look something like this (not tested):
std::vector<unsigned> v;
auto text_rule = *(*(axe::r_any() - axe::r_numstr()) & ~axe::r_numstr()
>> axe::e_push_back(v)) & axe::r_end();
// test it
std::string str("12 asdf789, 54,19 1000 nsfewer:22!13");
text_rule(str.begin(), str.end());
// print result
std::for_each(v.begin(), v.end(), [](unsigned i) { std::cout << i << '\n'; });
The basic idea it to skip all input characters which don't match the number string rule (r_numstr
).
精彩评论