RegexBuilder · regex answers
Regex for a URL
/^https?://[^\s/$.?#][^\s]*$/i
For links a user typed, you want a cheap sanity check, not a parser. This requires an http or https scheme and a host character that is not punctuation, which rejects the common paste accidents. For anything structural — reading the host, the port, the query — use your language's URL parser, which handles internationalised domains and percent-encoding that no regex should attempt.
What each part does
| https? | the literal http, with an optional s |
| :// | the scheme separator |
| [^\s/$.?#] | the first host character must not be a slash, dollar, dot, question mark or hash |
| [^\s]* | anything up to the first whitespace |
Tested against real input
Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.
| Input | Result | Matched |
|---|---|---|
| https://example.com | matches | https://example.com |
| http://example.com/path?q=1#top | matches | http://example.com/path?q=1#top |
| https://sub.example.co.uk:8443/x | matches | https://sub.example.co.uk:8443/x |
| example.com | no match | — |
| https:// | no match | — |
| ftp://example.com | no match | — |
| https:// example.com | no match | — |
The mistake to avoid
Trying to validate a URL and parse it with the same expression. Percent-encoding, IPv6 literals in brackets and internationalised hosts all break hand-rolled patterns; parse with a URL class instead.
Try it on your own text
Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.
Open RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID
- Regex for a hex colour code