RRegexBuilder
Get RegexBuilder

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.

InputResultMatched
https://example.commatcheshttps://example.com
http://example.com/path?q=1#topmatcheshttp://example.com/path?q=1#top
https://sub.example.co.uk:8443/xmatcheshttps://sub.example.co.uk:8443/x
example.comno match
https://no match
ftp://example.comno match
https:// example.comno 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 RegexBuilder

Other regex answers