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

解析url并替换C+中的协议和端口号+; 我尝试在C++中编写函数解析URL,从URL获取端口号和协议,用不同的端口号和协议替换。,c++,visual-c++,mfc,C++,Visual C++,Mfc,因为。如。 原始URL https://abc.com:8140/abc/bcd 我需要用http替换https,端口号为6143。并将URL路径合并为 http://abc.com:6143/abc/bcd 我使用的操作系统是Windows7和VisuladStudio 6.0 谢谢,您的问题的一个解决方案是。解析字符串中的令牌: > /C++ >将C++ 11代码改编成旧的C++。 #include "boost/regex.hpp" boost::regex re_protocol

因为。如。 原始URL

https://abc.com:8140/abc/bcd
我需要用http替换https,端口号为6143。并将URL路径合并为

http://abc.com:6143/abc/bcd
我使用的操作系统是Windows7和VisuladStudio 6.0


谢谢,

您的问题的一个解决方案是。

解析字符串中的令牌:

  • ^https?://要与协议匹配
  • :\d{1,5}/与端口号匹配
  • 刚刚开发并测试了使用

    现在,如果您查看下面的代码,我们将声明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;
    }
    

    注意,新的STL在Boost中有很大的灵感,你可以通过使用<代码> Boo::ReXEX <代码>代替<代码> STD::ReXEX < /C> > /C++ >将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/");
    

    使用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
    

    如果您向我们展示您的尝试,我们将更倾向于帮助您解决任何问题。不,最简单的解决方案是在字符数组中循环。正则表达式很难看,速度较慢,需要额外的技能,但它们会产生更小的代码。
    CString oldurl = L"https://abc.com:8140/abc/bcd";    
    CString newurl ;
    Replace(oldurl, newurl, L"6143") ;
    // now newurl contains the transformed URL