C++ Regular Expressions with Boost Regex

前端 未结 3 1319
忘掉有多难
忘掉有多难 2020-12-05 12:36

I am trying to take a string in C++ and find all IP addresses contained inside, and put them into a new vector string.

I\'ve read a lot of documentation on regex, b

3条回答
  •  情话喂你
    2020-12-05 13:05

    #include 
    #include 
    #include 
    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 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;
    }
    

提交回复
热议问题