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 here due to alternation) | N/A |
https? |
Matches 'http' followed by an optional 's' | http or https |
| |
Alternation: matches either the preceding or following pattern | Separates 'https?' and 'ftp' |
ftp |
Matches the literal string 'ftp' | ftp |
) |
End of the non-capturing group | N/A |
:// |
Matches the literal string '://' | :// in 'http://' |
[^\s/$.?#] |
Negated character class: matches any character except whitespace, '/', '$', '.', '?', or '#' | e in 'example.com' |
. |
Matches any single character (except newline) | x in 'example.com' |
[^\s]* |
Negated character class: matches zero or more characters that are not whitespace | ample.com/path |
$ |
Anchor: asserts position at end of the string | End of 'http://example.com/path' |
Matches
http://example.comhttps://example.com/pathftp://files.example.orghttp://sub.domain.co.uk/path?query=1#frag
Does not match
http:// example.comhttps://example.com pathftp://example..comhttp://example.com$pathhttp://example.com/path with space
Common pitfalls
- The pattern allows invalid domains like 'http://.com' because [^\s/$.?#] can match a dot immediately after '://'.
- The dot after [^\s/$.?#] is greedy and may match unintended characters if not constrained.
- No validation of domain structure (e.g., 'http://com' is technically matched).
- The pattern does not enforce valid TLDs or domain labels.
Performance notes
The pattern is generally efficient due to the use of negated character classes and anchors. However, the greedy [^\s]* at the end could lead to catastrophic backtracking if the input contains long sequences of non-whitespace characters. Anchoring (^ and $) ensures the regex matches the entire string, which is good for validation but may fail on partial matches.