我尝试用c ++编写函数来解析URL并从url获取端口号和协议,并用不同的端口号和协议替换。
有关。例如。 原始网址
https://abc.com:8140/abc/bcd
我需要用http和端口号替换https为6143.并将URL路径合并为
http://abc.com:6143/abc/bcd
我使用OS作为Windows 7和Visulad studio 6.0。
谢谢,
答案 0 :(得分:0)
问题的一个解决方案是regular expressions。
答案 1 :(得分:0)
答案 2 :(得分:0)
C ++ 11或Boost提供正则表达式支持。 在你的情况下,2个简单的表达式就足够了:
刚刚使用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
即可将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/");
答案 3 :(得分: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