迭代boost regex_iterator结果

时间:2014-01-21 19:00:33

标签: c++ regex boost lambda

我需要一些帮助来了解如何从boost :: sregex_iterator迭代搜索结果。基本上我在传递';'从命令行分隔的IP地址集,我希望能够使用boost :: sregex_iterator依次处理每个IP地址。

下面的代码演示了我要做的事情,并且还显示了使用 workingIterRegex 的变通方法 - 但是变通方法限制了我的正则表达式的丰富性。我尝试修改 nonworkingIterRegex ,但它只返回lambda的最后一个IP地址。

有没有人知道如何单独循环每个IP地址,而不必诉诸于这样一个被黑客攻击和简单化的workIterRegex。

我找到了以下http://www.cs.ucr.edu/~cshelton/courses/cppsem/regex2.cc来展示如何使用单个子匹配来调用lambda。

我还使用looping through sregex_iterator results中的示例来访问子匹配,但它给出了类似的结果。

使用workingIterRegex后,代码会打印出每行一个的IP地址

#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);
}
...

经过一些实验,我发现以下工作 - 但我不确定为什么c

1 个答案:

答案 0 :(得分:1)

尝试使用这样的正则表达式:

(\\d{1,3}\\.){3}(\\d{1,3})
相关问题