Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
( |
Start of non-capturing group (optional) | Optional group start |
https? |
Literal 'http' followed by optional 's' | http or https |
:// |
Literal characters '://' | :// |
)? |
End of group, quantifier: 0 or 1 occurrence | Optional http:// or https:// |
( |
Start of non-capturing group (optional) | Optional group start |
www\. |
Literal 'www.' | www. |
)? |
End of group, quantifier: 0 or 1 occurrence | Optional www. |
[-a-zA-Z0-9@:%._\+~#=] |
Character class: hyphen, letters, digits, @, :, %, ., _, +, ~, #, = | a-z, A-Z, 0-9, @, :, %, ., _, +, ~, #, - |
{1,256} |
Quantifier: between 1 and 256 occurrences of the preceding token | 1 to 256 characters |
\. |
Literal '.' (escaped) | . |
[a-zA-Z0-9()] |
Character class: letters, digits, parentheses | a-z, A-Z, 0-9, (, ) |
{1,6} |
Quantifier: between 1 and 6 occurrences of the preceding token | 1 to 6 characters |
\b |
Word boundary: asserts position between word and non-word character | End of TLD |
( |
Start of capturing group for path/query | Path/query start |
[-a-zA-Z0-9()@:%_\+.~#?&//=] |
Character class: hyphen, letters, digits, @, :, %, _, +, ., ~, #, ?, &, /, = | a-z, A-Z, 0-9, @, :, %, _, +, ., ~, #, ?, &, /, - |
* |
Quantifier: 0 or more occurrences of the preceding token | Zero or more path/query characters |
) |
End of capturing group | End of path/query |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
https://www.example.comhttp://example.com/path?query=1www.example.co.ukexample.comhttps://sub.domain.com:8080/path/to/resource?param=value#fragment
Does not match
ftp://example.comexample..comexample.cexample.123http://example.com/ invalidhttps://example.com/path with spaces
Common pitfalls
- Overly permissive character classes may match unintended characters (e.g., spaces in paths).
- The {1,256} quantifier may cause performance issues with very long strings due to backtracking.
- The \b word boundary may not work as expected with non-ASCII characters or trailing punctuation.
- The pattern does not validate TLDs against a list of known TLDs (e.g., .com, .org).
Performance notes
The pattern is generally efficient but may suffer from catastrophic backtracking if the input string is very long and contains many repeated characters in the domain or path segments. Anchoring (^ and $) ensures the entire string is validated. Consider using atomic groups or possessive quantifiers if performance is critical.