Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'http://example.com' |
( |
Start of a non-capturing group (though it captures due to ?: absence) | N/A |
[A-Za-z]+ |
Character class: one or more uppercase or lowercase letters | http, ftp, HTTPS |
: |
Literal colon character | : |
)? |
Quantifier: makes the preceding group (scheme) optional | Omitted in '//example.com' or present in 'http://example.com' |
\/\/ |
Literal double forward slash | // |
[^\/?#]+ |
Character class: one or more characters that are not '/', '?', or '#' | example.com, sub.domain.co.uk |
( |
Start of a capturing group for query parameters | N/A |
\? |
Literal question mark (start of query) | ? |
[^#]* |
Character class: zero or more characters that are not '#' | param=value&key=123 |
)? |
Quantifier: makes the preceding group (query) optional | Omitted in 'http://example.com' or present in 'http://example.com?foo=bar' |
( |
Start of a capturing group for fragment | N/A |
# |
Literal hash (start of fragment) | # |
.* |
Quantifier: zero or more of any character (except newline) | section1, top |
)? |
Quantifier: makes the preceding group (fragment) optional | Omitted in 'http://example.com' or present in 'http://example.com#top' |
$ |
Anchor: asserts position at end of the string | End of 'http://example.com/path?query#frag' |
Matches
http://example.comhttps://sub.domain.co.uk/path?query=value#sectionftp://files.example.org//example.comhttp://localhost:8080http://example.com?foo=barhttp://example.com#tophttp://example.com/path?query=value#frag
Does not match
example.comhttp:/example.comhttp//example.comhttp://example.com/path?query#frag?extrahttp://example.com#frag?queryhttp://example.com/path?query#frag extra
Common pitfalls
- Assuming the scheme must be present (it's optional)
- Not accounting for internationalized domain names (IDNs) which may contain non-ASCII characters
- Overlooking that the domain part cannot contain '/', '?', or '#'
- Ignoring that the fragment can contain any characters, including '?'
- Assuming the query must be present if the fragment is present (both are optional independently)
Performance notes
The pattern is linear in complexity and does not pose a catastrophic backtracking risk. However, overly broad patterns like '.*' in the fragment group can be inefficient for very long strings. Anchors (^ and $) ensure the entire string is matched, which is efficient.