C++的c11标准中新增了对正则表达式的支持,使得从字符串中正则提取出IP的代码更加简洁优雅,如下所示是我编译测试过的从一小段字符串中获取一个IP地址和从字符串中获取所有的IP地址的代码:
#include <regex>
#include <iostream>
#include <list>
using namespace std;
// [::ffff:192.168.1.6]:63332中提取出需要的IP
string get_ip_from_endpoint(const string &endpoint)
{
::regex pattern("(\\d+.){3}\\d+");
::smatch result;
if (regex_search(endpoint, result, pattern))
{
return result.str();
}
return "";
}
void get_ip_list_from_str(const string &str, list<string> &iplist)
{
::regex pattern("(\\d+.){3}\\d+");
::smatch result;
string::const_iterator iterStart = str.begin();
string::const_iterator iterEnd = str.end();
while (regex_search(iterStart, iterEnd, result, pattern))
{
string ip = result[0];
iplist.push_back(ip);
iterStart = result[0].second;
}
}
int main()
{
string endpoint = "[::ffff:222.168.2.222]";
cout << "IP: " << endpoint << endl;
cout << "IP list: ";
string str = "[::ffff:222.168.2.222]:63332[::ffff:222.1.1.222]:63332";
list<string> iplist;
get_ip_list_from_str(str, iplist);
for (auto iter = iplist.begin(); iter != iplist.end(); iter++)
cout << *iter << "; ";
cout << endl;
return 0;
}