之前使用boost解析字符串,因为编译跨平台的boost比较麻烦,现在尝试使用C++11,效果一样,以下是一个解析url的简单demo
#include <iostream>
#include <regex>
int url2domain(const std::string &url, std::string &domain, unsigned &port)
{
int ret = -1;
//使用迭代器拆分字符串 http://www.cppprog.com/2009/0112/48.html
std::regex reg_domain_port("/"); //按/符拆分字符串
std::cregex_token_iterator itrBegin(url.c_str(), url.c_str() + url.size(), reg_domain_port, -1);
std::cregex_token_iterator itrEnd;
int i = 0;
std::string domain_port;
for (std::cregex_token_iterator itr = itrBegin; itr != itrEnd; ++itr)
{
i++;
if (i == 3)
{
domain_port = *itr;
}
}
if (domain_port.size() == 0)
{
domain_port = url;
}
//考虑带端口的情况
std::regex reg_port(":");
std::cregex_token_iterator itrBegin2(domain_port.c_str(), d