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.
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 a named-group lookup 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
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. The match exposes them through lookups such as
match.group('host') and match.group('query').
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
Following a grammar gives each branch of the expression a requirement to check against. It still leaves room for implementation mistakes and unsupported cases, but makes the intended handling of hosts, ports and paths explicit instead of relying on a collection of examples.