0

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

为了。例如。原始网址

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

我需要将 https 替换为 http 和端口号为 6143。并合并 URL 路径,如

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

我将操作系统用作 Windows 7 和 Visulad Studio 6.0。

谢谢,

4

4 回答 4

0

您的问题的一种解决方案是正则表达式

于 2013-07-31T13:01:05.433 回答
0

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

于 2013-07-31T13:08:03.540 回答
0

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

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

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

现在,如果您查看下面的代码,我们声明 2 正则表达式并使用 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.

#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/");
于 2013-07-31T15:56:46.360 回答
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
于 2013-07-31T16:03:26.447 回答