带有Boost Regex的C ++正则表达式

时间:2011-04-27 12:55:23

标签: c++ regex boost boost-regex

我正在尝试在C ++中获取一个字符串并查找其中包含的所有IP地址,并将它们放入一个新的矢量字符串中。

我已经阅读了很多关于正则表达式的文档,但我似乎无法理解如何做这个简单的函数。

我相信我可以使用这个Perl表达式来查找任何IP地址:

re("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");

但我仍然对如何做其余事情感到难过。

3 个答案:

答案 0 :(得分:14)

也许你正在寻找这样的东西。它使用regex_iterator来获取当前模式的所有匹配项。请参阅reference

#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main()
{
    std::string text(" 192.168.0.1 abc 10.0.0.255 10.5.1 1.2.3.4a 5.4.3.2 ");
    const char* pattern =
        "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
        "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
    boost::regex ip_regex(pattern);

    boost::sregex_iterator it(text.begin(), text.end(), ip_regex);
    boost::sregex_iterator end;
    for (; it != end; ++it) {
        std::cout << it->str() << "\n";
        // v.push_back(it->str()); or something similar     
    }
}

输出:

192.168.0.1
10.0.0.255
5.4.3.2

旁注:你可能意味着\\b而不是\b;我怀疑你是否喜欢匹配退格角色。

答案 1 :(得分:-1)

提供的解决方案非常好,谢谢它。虽然我发现模式本身有轻微错误。

例如,49.000.00.01之类的内容将被视为有效的IPv4地址,根据我的理解,它不应该(在某些转储处理期间发生在我身上)。

我建议将模式改进为:

"\\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)"
"\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)"
"\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)"
"\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\\b";

这应该只允许0.0.0.0作为全零入口,我认为这是正确的,它将消除所有.00。 .000。等

答案 2 :(得分:-1)

#include <string>
#include <list>
#include <boost/regex.hpp>
typedef std::string::const_iterator ConstIt;

int main()
{
    // input text, expected result, & proper address pattern
    const std::string sInput
    (
            "192.168.0.1 10.0.0.255 abc 10.5.1.00"
            " 1.2.3.4a 168.72.0 0.0.0.0 5.4.3.2"
    );
    const std::string asExpected[] =
    {
        "192.168.0.1",
        "10.0.0.255",
        "0.0.0.0",
        "5.4.3.2"
    };
    boost::regex regexIPs
    (
        "(^|[ \t])("
        "(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])[.]"
        "(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])[.]"
        "(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])[.]"
        "(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])"
        ")($|[ \t])"
    );

    // parse, check results, and return error count
    boost::smatch what;
    std::list<std::string> ns;
    ConstIt end = sInput.end();
    for (ConstIt begin = sInput.begin();
                boost::regex_search(begin, end, what, regexIPs);
                begin = what[0].second)
    {
        ns.push_back(std::string(what[2].first, what[2].second));
    }

    // check results and return number of errors (zero)
    int iErrors = 0;
    int i = 0;
    for (std::string & s : ns)
        if (s != asExpected[i ++])
            ++ iErrors;
    return iErrors;
}