I had recently written regexes to parse contens in my file but that one was in .NET and I just started using Boost now for my C++ project.

I have a line similar to the following, which is a std::string
123 12 E

that I have to parse and get the following.

float = first digit
float = second digit
string = third alphabet

Since I have experience using regexes, I know what the regex is

const char* Regex = "^[[:space:]]*(\\d{1,3})[[:space:]]*(\\d{1,2})[[:space:]]*([NSEW])[[:space:]]*"

But I am not sure how to use this with boost to extract the three things from my line. I tried reading examples on Boost website and that didn't seem to answer my question since I would have to bog down to find this little detail. how do I use Boost Regex with the above regex to get my result out in three variable?

有帮助吗?

解决方案

http://www.boost.org/doc/libs/1_52_0/libs/regex/doc/html/boost_regex/introduction_and_overview.html gives example of matching. You end up with a match_results structure which you can get the matches from.

Untested code

const char *str = "123 12 E";
boost::regex re ("^(\\d{1,3}) (\\d{1,2}) ([NSEW])$");
boost::cmatch mr;
if (boost::regex_match ( str, mr, re )) {
    std::cout << "There were: " << mr.size () - 1 << " fields matched" << std::endl;
    std::cout << "First part: " << mr[1] << std::endl;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top