#include <iostream>
#include <regex>
#include <string>
int main() {
// 定义一个正则表达式,匹配以 "http" 或 "https" 开头的 URL
std::regex url_regex("https?://([\\w.-]+)(:\\d+)?(/[^\\s]*)?");
// 测试字符串
std::string test_str = "Visit https://www.example.com:8080/path for more info or http://example.org";
// 使用 std::smatch 来存储匹配结果
std::smatch match_results;
// 遍历测试字符串,查找所有匹配的 URL
auto words_begin = std::sregex_iterator(test_str.begin(), test_str.end(), url_regex);
auto words_end = std::sregex_iterator();
// 输出所有匹配的 URL
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::cout << "Found URL: " << match.str() << '\n';
}
return 0;
}
<iostream> 用于输入输出,<regex> 用于正则表达式处理,<string> 用于字符串操作。std::regex url_regex("https?://([\\w.-]+)(:\\d+)?(/[^\\s]*)?"); 定义了一个正则表达式,用于匹配以 http 或 https 开头的 URL。具体解释如下:https?:匹配 http 或 https。://:匹配 ://。([\\w.-]+):匹配主机名部分,允许字母、数字、下划线、点和连字符。(:\\d+)?:可选的端口号部分。(/[^\\s]*)?:可选的路径部分,直到遇到空格为止。std::string test_str = "Visit https://www.example.com:8080/path for more info or http://example.org"; 定义了一个包含多个 URL 的字符串。std::sregex_iterator 遍历字符串,查找所有符合正则表达式的子串。这个示例展示了如何在 C++ 中使用正则表达式来查找并提取 URL。
上一篇:c++ socket
下一篇:c++运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站