Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | http://example.com |
(https?|ftp) |
Group: matches either 'http' (with optional 's') or 'ftp' | http, https, ftp |
? |
Quantifier: makes the preceding group (s) optional | http://, https:// |
: |
Literal colon character | http: |
\/\/ |
Literal forward slashes (escaped) | http:// |
(www\.)? |
Group: matches 'www.' literally, optional | www., (empty) |
[-a-zA-Z0-9@:%._\+~#=]{1,256} |
Character class: matches domain name parts (1-256 chars), including hyphens, alphanumeric, and symbols | example, sub-domain |
\. |
Literal dot character (escaped) | .com |
[a-zA-Z0-9()]{1,6} |
Character class: matches TLD (1-6 chars), alphanumeric or parentheses | com, org, io |
\b |
Word boundary anchor | example.com |
([-a-zA-Z0-9()@:%_\+.~#?&\/=]*) |
Group: matches path, query, or fragment (0 or more chars), including symbols | /path?query=value#fragment |
$ |
Anchor: asserts position at end of the string | http://example.com/path |
Matches
http://example.comhttps://www.example.comftp://sub.domain.co.uk/path?query=valuehttp://localhost:8080https://user:pass@secure.example.org
Does not match
example.comhttp//example.comhttp:/example.comhttp://example..comhttp://-example.comhttp://example.com/ pathhttp://example.c
Common pitfalls
- Fails to match URLs without protocol (e.g., 'example.com').
- Does not validate TLDs strictly (e.g., 'http://example.c' matches).
- Overly permissive with symbols in domain names (e.g., 'http://exa_mple.com').
- Does not handle internationalized domain names (IDNs).
- May match invalid paths with spaces (though \b helps).
Performance notes
Low risk of catastrophic backtracking due to bounded quantifiers. Anchors (^ and $) ensure full-string matching, preventing partial matches.