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

2021-12-24 00:00:00 regex c++ boost boost-regex

我试图在 C++ 中获取一个字符串并找到其中包含的所有 IP 地址,并将它们放入一个新的向量字符串中.

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, but I just can't seem to understand how to do this simple function.

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

I believe I can use this Perl expression to find any IP address:

re("(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]?)");

但我仍然不知道如何做剩下的事情.

But I am still stumped on how to do the rest.

推荐答案

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

Perhaps you're looking for something like this. It uses regex_iterator to get all matches of the current pattern. See 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() << "
";
        // v.push_back(it->str()); or something similar     
    }
}

输出:

192.168.0.1
10.0.0.255
5.4.3.2

旁注:你可能指的是 \b 而不是 ;我怀疑你想要匹配退格字符.

Side note: you probably meant \b instead of ; I doubt you watnted to match backspace character.

相关文章