Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
(https?://)? |
Optional group matching 'http://' or 'https://' | http:// or https:// or nothing |
? |
Quantifier: 0 or 1 occurrence of the preceding group | Absent or present once |
(www\.)? |
Optional group matching 'www.' | www. or nothing |
? |
Quantifier: 0 or 1 occurrence of the preceding group | Absent or present once |
[-a-zA-Z0-9@:%._\+~#=]{1,256} |
Character class matching 1 to 256 of allowed URL characters (domain part) | example.com or sub.domain |
\. |
Literal dot character | . |
[a-zA-Z0-9()]{1,6} |
Character class matching 1 to 6 of allowed TLD characters | com or org or io |
\b |
Word boundary anchor | End of TLD |
(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*) |
Non-capturing group matching 0 or more URL path/query characters | /path?query=value or / or empty |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
http://example.comhttps://www.example.com/path?query=valueexample.comwww.example.orghttps://sub.domain.co.uk/page#sectionhttp://user:pass@domain.comhttps://domain.com/?q=test&lang=en
Does not match
ftp://example.comexample..comexample.cexample.commexample.com/path with spaceshttp://example.com:99999http://example.com/path?query=value#fragment with spaces
Common pitfalls
- Overly permissive character classes may match invalid or malformed URLs
- No strict validation of TLD length or structure (e.g., 'com' vs 'c' is allowed)
- Allows URLs with spaces or other unsafe characters in the path/query
- Does not enforce valid port numbers (e.g., ':99999' is technically matched)
- May match strings with invalid domain structures (e.g., 'example..com')
- No validation of internationalized domain names (IDNs)
Performance notes
Low risk of catastrophic backtracking due to bounded quantifiers ({1,256}, {1,6}, *). Anchors (^ and $) ensure efficient matching. Consider stricter patterns for production use.