Skip to content

Personal

URI Generic Regex

A single Python regular expression that decomposes a URI into its RFC 3986 components as named capture groups: scheme, userinfo, host, port, path, query, fragment.

May 2025Developer toolsMeasurement

One regular expression, one file. It splits a URI into the components RFC 3986 defines and hands each one back as a named group, so extracting the host or the query is an attribute access rather than a second parse.

Size
One module, a regex and a demo entry point
Groups
scheme · userinfo · host · domain · localhost · port · path · query · fragment
Covers
Domain names, IPv4 and IPv6 literals
Repository
VincenzoImp/uri-generic-regex
VincenzoImp/uri-generic-regexA Python regular expression for parsing URI components per RFC 3986, with named capture groups.Python

What it is

The URI regexes that circulate online mostly answer “does this look like a link?”, which is a different question from “what are its parts?”, and they tend to be assembled by hand from examples rather than from the grammar. This one follows the RFC’s own component definitions and names each capture after the component it holds, which is the entire ergonomic point: a match object where host and query are attributes.

The host branch distinguishes a domain name from an IPv4 literal, an IPv6 literal in brackets, and localhost, because those are four different shapes and collapsing them is where the copied regexes usually go wrong.

What I took from it

A regular expression derived from a grammar and one derived from examples fail differently. The example-derived kind works on everything you thought of and silently mis-parses the rest; the grammar-derived kind is longer, harder to read, and wrong only where you misread the specification. For something that runs over URLs at scale, that second failure mode is the one worth having, and it is why the acquisition work that uses it starts from the RFC rather than from a snippet.