visual解析url并替换C++中的协议和端口号

visual parsed the url and replace the protocol and port number in C++

本文关键字:协议 口号 C++ 解析 url 替换 visual      更新时间:2023-10-16

我正在尝试用c++编写函数来解析URL,并从URL中获取端口号和协议,并替换为不同的端口号和端口协议。

对于。例如。原始URL

https://abc.com:8140/abc/bcd

我需要将https替换为http,端口号为6143。并像一样合并了URL路径

http://abc.com:6143/abc/bcd

我使用的操作系统是Windows7和Visulad studio 6.0。

谢谢,

MFC快速肮脏的解决方案:

static TCHAR strhttp[] = L"http:" ;
void Replace(CString & oldurl, CString & newurl, LPTSTR newport)
{
  int colonposition ;
  colonposition = oldurl.Find(':') ;
  if (colonposition != -1)
  {
    newurl = (CString)strhttp + oldurl.Mid(colonposition + 1) ;
    colonposition = newurl.Find(':', _tcslen(strhttp) + 1) ;
    if (colonposition != -1)
    {
      int slashposition = newurl.Find('/', colonposition) ;
      newurl = newurl.Left(colonposition + 1) + newport + newurl.Mid(slashposition) ;
    }
  }
}

用法:

CString oldurl = L"https://abc.com:8140/abc/bcd";    
CString newurl ;
Replace(oldurl, newurl, L"6143") ;
// now newurl contains the transformed URL

问题的一个解决方案是正则表达式。

分析字符串中的令牌:http://msdn.microsoft.com/en-us/library/2c8d19sb(v=vs.71).aspx

C++11或Boost提供正则表达式支持。在您的情况下,2个简单的表达式就足够了:

  1. ^https?://为了与协议相匹配
  2. :\d{1,5}/与端口号匹配

刚刚使用开发并测试了这2个正则表达式http://www.regextester.com/

现在,如果您查看下面的代码,我们声明2 regex,并使用C++11 STL附带的regex_replace函数。

#include <string>
#include <regex>
#include <iostream>
int main(int argc, char* argv[])
{
    std::string input ("https://abc.com:8140/abc/bcd");
    std::string output_reference ("http://abc.com:6143/abc/bcd");
     std::regex re_protocol ("^https?://");  //https to http
     std::regex re_port(":\d{1,5}/"); //port number replacement, NB note that we use \d.
     std::string result = std::regex_replace(std::regex_replace (input, re_protocol, "http://"), re_port, ":6143/");
     if(output_reference != result) {
         std::cout << "error." << std::endl;
         return -1; 
     }
     std::cout << input << " ==> " <<   result << std::endl;
     return 0;
}

结果是

https://abc.com:8140/abc/bcd ==> http://abc.com:6143/abc/bcd

注意,由于新的STL在Boost中获得了很大的灵感,您可以通过使用boost::regex而不是std::regex来将C++11代码改编为旧的C++。

#include "boost/regex.hpp"
boost::regex re_protocol ("^https?://");  //https to http
boost::regex re_port(":\d{1,5}/"); //port number replacement, NB note that we use \d.      
std::string result = boost::regex_replace(boost::regex_replace (input, re_protocol, "http://"), re_port, ":6143/");