C++ Regular Expressions with Boost Regex(带有 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++ 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 Boost Regex 的 C++ 正则表达式
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
