How to parse URL (protocol, host, path) in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <regex>

struct URL {
    std::string protocol;
    std::string host;
    std::string path;
};

URL parse_url(const std::string &url) {
    std::regex url_regex(R"(^(https?)://([^/]+)(/.*)?$)");
    std::smatch url_match;

    URL parsed_url;

    if (std::regex_match(url, url_match, url_regex)) {
        parsed_url.protocol = url_match[1].str();
        parsed_url.host = url_match[2].str();
        parsed_url.path = url_match[3].str();
    }

    return parsed_url;
}

int main() {
    std::string url = "https://www.collectivesolver.com/path/to/resource";
    
    URL parsed_url = parse_url(url);

    std::cout << "Protocol: " << parsed_url.protocol << "\n";
    std::cout << "Host: " << parsed_url.host << "\n";
    std::cout << "Path: " << parsed_url.path << "\n";
}


/*
run:

Protocol: https
Host: www.collectivesolver.com
Path: /path/to/resource

*/

 



answered Jan 31, 2025 by avibootz

Related questions

1 answer 192 views
192 views asked Jan 31, 2025 by avibootz
2 answers 450 views
2 answers 584 views
584 views asked Mar 31, 2018 by avibootz
1 answer 246 views
1 answer 314 views
2 answers 421 views
...