Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ regex

作者:戮尽逆者   发布日期:2025-07-27   浏览:14

#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;
}

解释说明:

  1. 引入头文件#include <regex> 引入了 C++ 标准库中的正则表达式功能。
  2. 定义正则表达式std::regex url_regex("https?://([\\w.-]+)(:\\d+)?(/[^\\s]*)?"); 定义了一个正则表达式,用于匹配以 httphttps 开头的 URL。这个正则表达式的含义如下:
    • https?:匹配 httphttpss 是可选的)。
    • ://:匹配 ://
    • ([\\w.-]+):匹配域名部分,由字母、数字、下划线、点或连字符组成。
    • (:\\d+)?:匹配端口号部分(可选),例如 :8080
    • (/[^\\s]*)?:匹配路径部分(可选),例如 /path/to/resource
  3. 测试字符串std::string test_url = "https://www.example.com:8080/path/to/resource?query=string"; 定义了一个测试 URL 字符串。
  4. 创建迭代器auto words_begin = std::sregex_iterator(test_url.begin(), test_url.end(), url_regex);auto words_end = std::sregex_iterator(); 创建了两个迭代器,用于遍历所有匹配项。
  5. 遍历匹配项:使用 for 循环遍历所有匹配项,并输出每个匹配项及其捕获组的内容。
  6. 输出捕获组内容:通过 match[1], match[2], match[3] 分别获取域名、端口和路径部分的内容,并输出。

这个示例展示了如何使用 C++ 的正则表达式库来匹配和解析 URL。

上一篇:c++或

下一篇:c++换行符

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站