#include <iostream>
#include <regex>
#include <string>
int main() {
// 定义一个正则表达式,用于匹配以 "http" 或 "https" 开头的 URL
std::regex url_regex("https?://([\\w.-]+)(:\\d+)?(/[^\\s]*)?");
// 测试字符串
std::string test_url = "https://www.example.com:8080/path/to/resource?query=string";
// 创建一个迭代器,用于遍历所有匹配项
auto words_begin = std::sregex_iterator(test_url.begin(), test_url.end(), url_regex);
auto words_end = std::sregex_iterator();
// 遍历所有匹配项并输出
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::cout << "Found match: " << match.str() << '\n';
// 输出捕获组的内容
if (match[1].matched) {
std::cout << "Domain: " << match[1] << '\n';
}
if (match[2].matched) {
std::cout << "Port: " << match[2] << '\n';
}
if (match[3].matched) {
std::cout << "Path: " << match[3] << '\n';
}
}
return 0;
}
#include <regex>
引入了 C++ 标准库中的正则表达式功能。std::regex url_regex("https?://([\\w.-]+)(:\\d+)?(/[^\\s]*)?");
定义了一个正则表达式,用于匹配以 http
或 https
开头的 URL。这个正则表达式的含义如下:https?
:匹配 http
或 https
(s
是可选的)。://
:匹配 ://
。([\\w.-]+)
:匹配域名部分,由字母、数字、下划线、点或连字符组成。(:\\d+)?
:匹配端口号部分(可选),例如 :8080
。(/[^\\s]*)?
:匹配路径部分(可选),例如 /path/to/resource
。std::string test_url = "https://www.example.com:8080/path/to/resource?query=string";
定义了一个测试 URL 字符串。auto words_begin = std::sregex_iterator(test_url.begin(), test_url.end(), url_regex);
和 auto words_end = std::sregex_iterator();
创建了两个迭代器,用于遍历所有匹配项。for
循环遍历所有匹配项,并输出每个匹配项及其捕获组的内容。match[1]
, match[2]
, match[3]
分别获取域名、端口和路径部分的内容,并输出。这个示例展示了如何使用 C++ 的正则表达式库来匹配和解析 URL。
上一篇:c++或
下一篇:c++换行符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站