Reputation: 2642
I need some help to understand how to iterate over the search results from a boost::sregex_iterator. Basically I am passing in a ';' delimited set of IP addresses from the command line, and I would like to be able to process each IP address in turn using a boost::sregex_iterator.
The code below demonstrates what I am trying to do and also shows a workaround using the workingIterRegex - however the workaround limits the richness of my regular expression. I tried modifying the nonworkingIterRegex however it only returns the last IP address to the lambda.
Does anyone know how I can loop over each IP address individually without having to resort to such a hacked and simplistic workingIterRegex.
I found the following http://www.cs.ucr.edu/~cshelton/courses/cppsem/regex2.cc to show how to call the lambda with the individual sub matches.
I also used the example in looping through sregex_iterator results to get access to the sub matches however it gave similar results.
After using the workingIterRegex the code prints out the IP addresses one per line
#include <string>
#include <boost/regex.hpp>
...
std::string errorMsg;
std::string testStr("192.168.1.1;192.168.33.1;192.168.34.1;192.168.2.1");
static const boost::regex nonworkingIterregex (
"((\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3});?)+",
boost::regex_constants::icase);
boost::smatch match;
if (boost::regex_match(testStr, match, nonworkingIterregex)) {
static const boost::regex workingIterRegex("[^;]+");
std::for_each(boost::sregex_iterator(
begin(iter->second), end(iter->second), workingIterRegex),
boost::sregex_iterator(),
[](const boost::smatch &match){
std::cout << match.str() << std::endl;
}
);
mNICIPAddrs = UtlStringUtils::tokenize(iter->second, ";");
std::string errorMsg;
} else {
errorMsg = "Malformed CLI Arg:" + iter->second;
}
if (!errorMsg.empty()) {
throw std::invalid_argument(errorMsg);
}
...
After some experimentation I found that the following worked - but I am not sure why the c
Upvotes: 2
Views: 1250
Reputation: 47169
Try using your regex expression like this:
(\\d{1,3}\\.){3}(\\d{1,3})
Upvotes: 1