A C++ header-only library inspired by path-to-regexp, designed for compiling path patterns into regular expressions and extracting dynamic segments from paths.
#include <iostream>
#include <path_to_regex.hpp>
int main()
{
auto matcher = path_to_regex::match("/api/v1/download/:file{.:ext}");
auto [matched, params] = matcher("/api/v1/download/archive.zip");
if (matched)
std::cout << "File '" << params["file"] << "' with extension '" << params["ext"] << "' requested" << std::endl;
else
std::cerr << "Wrong path" << std::endl;
return EXIT_SUCCESS;
}
Parameters capture arbitrary strings in a path by matching up to the end of a segment or the next token. They are defined by placing a colon before the parameter name (:foo), with names consisting of alphanumeric characters.
auto matcher = path_to_regex::match("/:category/:id");
auto [matched, params] = matcher("/products/123");
//=> matched: true, params: {{"category", "products"}, {"id", "123"}}
Braces can be used to specify optional sections within a path.
auto matcher = path_to_regex::match("/download/:file{.:ext}");
auto [matched, params] = matcher("/download/archive");
//=> matched: true, params: {{ "file", "archive"}, {"ext", ""}}
auto [matched, params] = matcher("/download/archive.zip");
//=> matched: true, params: {{ "file", "archive"}, {"ext", "zip"}}
Wildcard parameters can match multiple characters across several segments. They are similar to regular parameters but are defined by prefixing the parameter name with an asterisk (*foo).
auto matcher = path_to_regex::match("/*foo");
matcher("/bar/baz");
//=> matched: true, params: {{ "foo", "bar/baz"}}
This code is distributed under the MIT License