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 |
https? |
Matches 'http' followed by an optional 's' | http or https |
| |
Alternation: matches either the preceding or following pattern | N/A |
ftp |
Matches the literal string 'ftp' | ftp |
) |
End of the capturing group | N/A |
: |
Matches the literal colon character | : |
\/\/ |
Matches the literal string '://' (escaped forward slashes) | :// |
[^\s\/$\.?#] |
Matches any single character except whitespace, /, $, ., ?, or # | e in 'example' |
. |
Matches any single character except newline | x in 'example.com' |
[^\s]* |
Matches zero or more characters that are not whitespace | ample.com/path?query=1 |
$ |
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/page?query=1https://192.168.1.1:8080
Does not match
http:/example.comhttps//example.comftp:example.comhttp://example.com with spacehttp://example..comhttp://example.com$invalidexample.comhttp://
Common pitfalls
- Forgetting to escape forward slashes in the protocol separator (://).
- Assuming the pattern matches all valid URLs (e.g., it rejects URLs with spaces or certain special characters).
- Overlooking that the first character after :// must not be whitespace or /$?.#.
- Not accounting for internationalized domain names (IDNs) or Unicode characters.
Performance notes
The pattern is generally efficient due to the use of negated character classes and anchors. However, the `[^\s]*` at the end could match very long strings, potentially causing performance issues if the input is extremely large. The alternation `(https?|ftp)` is simple and does not introduce significant backtracking.