Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'http://example.com' |
( |
Start of a capturing group | N/A |
http |
Literal characters 'http' | http |
| |
Alternation (OR operator) | N/A |
https |
Literal characters 'https' | https |
) |
End of capturing group | N/A |
:// |
Literal characters '://' | :// |
[a-zA-Z0-9\-]+ |
Character class matching one or more alphanumeric characters or hyphens | example, test-123 |
( |
Start of a non-capturing group (implicit in Python regex) | N/A |
\. |
Literal dot (escaped) | . |
[a-zA-Z0-9\-]+ |
Character class matching one or more alphanumeric characters or hyphens | com, sub-domain |
)* |
Quantifier: zero or more repetitions of the preceding group | .com, .co.uk |
( |
Start of a non-capturing group | N/A |
:\d+ |
Literal colon followed by one or more digits (port number) | :8080 |
)? |
Quantifier: zero or one repetition of the preceding group | :8080 or absent |
( |
Start of a non-capturing group | N/A |
/[^\s]* |
Literal slash followed by zero or more non-whitespace characters | /path/to/resource |
)? |
Quantifier: zero or one repetition of the preceding group | /path or absent |
$ |
Anchor: asserts position at end of the string | End of 'http://example.com/path' |
Matches
http://example.comhttps://sub.domain.co.uk:8080/path/to/resourcehttp://test-123.comhttps://a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.zhttp://localhost:3000https://123-abc.def.ghi
Does not match
ftp://example.comhttp://example..comhttp://example.com/path with spaceshttp://-example.comhttp://example.com:http://example.com:abchttp://example.com/path?query=value
Common pitfalls
- Forgetting to escape the dot in the domain part (should be \. instead of .).
- Not anchoring the regex with ^ and $, leading to partial matches.
- Assuming the regex handles all valid URLs (e.g., internationalized domain names or IPv6 addresses).
- Overlooking that the path part does not allow spaces (uses [^\s]*).
- Not accounting for uppercase/lowercase letters in the protocol (e.g., HTTP://example.com).
Performance notes
The pattern is generally efficient due to limited quantifiers and alternations. However, the nested quantifiers (e.g., * for subdomains) could lead to catastrophic backtracking if the input is maliciously crafted with many subdomains. Consider using possessive quantifiers or atomic groups if performance is critical.