C ++普通防爆pressions与升压正则表达式 [英] C++ Regular Expressions with Boost Regex

查看:128
本文介绍了C ++普通防爆pressions与升压正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图采取在C ++字符串,并发现里面包含了所有的IP地址,并把它们放入一个新的向量的字符串。

我已经读了很多关于正则表达式的文件,但我似乎无法理解如何做到这一点简单的功能。

我相信我可以用这个Perl的前pression找到任何IP地址:

<$p$p><$c$c>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\");

但我还是难倒如何做休息。


解决方案

也许你正在寻找这样的事情。它采用 regex_iterator 来获得当前模式的所有比赛。见<一href=\"http://www.boost.org/doc/libs/1_46_1/libs/regex/doc/html/boost_regex/ref/regex_iterator.html\">reference.

 的#include&LT;升压/ regex.hpp&GT;
#包括LT&;&iostream的GT;
#包括LT&;串GT;诠释的main()
{
    标准::字符串文本(192.168.0.1 ABC 10.0.0.255 10.5.1 1.2.3.4a 5.4.3.2);
    为const char *模式=
        \\\\ 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]?)\\\\湾;
    提高::正则表达式ip_regex(模式);    提高:: sregex_iterator它(text.begin(),text.end(),ip_regex);
    提高:: sregex_iterator结束;
    为(;!它=结束;它++){
        性病::法院LT&;&LT; IT-&GT; STR()&LT;&LT; \\ n;
        // v.push_back(IT-&GT; STR());或类似的东西
    }
}

输出:

  192.168.0.1
10.0.0.255
5.4.3.2

旁注:你可能是指 \\\\ b 而不是 \\ b ;我怀疑你watnted匹配退格字符。

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.

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

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");

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

解决方案

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() << "\n";
        // v.push_back(it->str()); or something similar     
    }
}

Output:

192.168.0.1
10.0.0.255
5.4.3.2

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

这篇关于C ++普通防爆pressions与升压正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆