写一个cpp函数, 用于拆解各种url, 包括tcp://ip:port 形式
时间: 2024-02-01 21:02:01 浏览: 35
好的,下面是一个简单的 C++ 函数,可以用于拆解各种 URL,包括 `tcp://ip:port` 形式:
```cpp
#include <iostream>
#include <string>
#include <regex>
using namespace std;
void parseURL(string url) {
regex pattern("^(\\w+):\\/\\/([\\w\\.]+):(\\d+)$");
smatch match;
if (regex_search(url, match, pattern)) {
string protocol = match[1];
string ip = match[2];
string port = match[3];
cout << "Protocol: " << protocol << endl;
cout << "IP: " << ip << endl;
cout << "Port: " << port << endl;
} else {
cout << "Invalid URL!" << endl;
}
}
int main() {
string url = "tcp://127.0.0.1:8080";
parseURL(url);
return 0;
}
```
这个函数使用了 C++11 的正则表达式库,匹配了 `tcp://ip:port` 格式的 URL,并提取了协议、IP 和端口号。如果 URL 格式不正确,则会输出错误信息。你可以将需要解析的 URL 作为参数传递给 `parseURL` 函数即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)