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