visual解析url并替换C++中的协议和端口号
visual parsed the url and replace the protocol and port number in C++
我正在尝试用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个简单的表达式就足够了:
- ^https?://为了与协议相匹配
- :\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/");
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 如何使用url确定网站协议
- 使用 VID、PID、+SN 查找 USB 端口号
- MSYS2 MinGW程序包中缺少grpc_cpp_plugin协议
- 用CMake构建C++协议
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何使用ZeroMQ为协议缓冲区编写自己的RPC实现
- 协议缓冲区字符串字段的文本编码
- 如何使用librdkafka设置明文协议(无SASL)的用户名和密码?
- 构建使用协议缓冲区(不含 APK)的 Android 可执行 gRPC 服务器
- 用于处理多个通信协议处理的设计类
- 无法使用 ReadBinaryProto Tensorflow 加载协议缓冲区
- 协议缓冲区的静态链接会导致与现有符号冲突
- 协议缓冲区ParseFromString不检查消息结尾
- 如何自定义wxApp来实现协议
- 与Qt交叉编译到Raspberry Pi 3B+通讯录(协议缓冲区)-错误符号查找错误
- 编译的谷歌协议缓冲区不工作(C++)
- 使用协议缓冲区创建通用反序列化程序
- 在协议缓冲区 c++ 中反序列化字符串数组
- visual解析url并替换C++中的协议和端口号