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

编程入门 行业动态 更新时间:2024-10-27 23:24:03
本文介绍了带有 Boost Regex 的 C++ 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我试图在 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.

这篇关于带有 Boost Regex 的 C++ 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 08:47:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/826471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   Boost   Regex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!