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

2023-07-20C/C++开发问题
2

本文介绍了带有 Boost Regex 的 C++ 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图在 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++ 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6