devkult_
tools26converters34

Regex for URL Validation

This pattern validates web URLs: an http or https scheme, a dotted hostname, and any path, query, or fragment after it. It's deliberately scoped to the URLs people paste into forms — for full RFC 3986 parsing (ports, userinfo, IPv6 hosts), use your language's URL parser and check the result instead.

/^https?:\/\/[\w.-]+(?:\.[\w-]+)+[^\s]*$/

How it works, token by token

TokenMeaning
^https?the scheme: http with an optional s
:\/\/the literal :// (slashes escaped)
[\w.-]+the first hostname label(s): word characters, dots, hyphens
(?:\.[\w-]+)+at least one more dotted label — requires a real domain, not just localhost
[^\s]*the rest of the URL: path, query, fragment — anything but whitespace
$end of string

What it matches

https://www.devkult.com
http://example.com/path?q=1#top
https://sub.domain.io/a/b
ftp://example.com
www.example.com
https://localhost

Try it live

One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.

/

Variations

^(?:https?:\/\/)?[\w.-]+(?:\.[\w-]+)+[^\s]*$scheme optional — also accepts www.example.com
https?:\/\/[^\s]+unanchored — extract URLs out of running text with the g flag

Language notes

  • JavaScript: for validation (not extraction), new URL(s) in a try/catch is often more reliable than any regex.
  • The \/ escapes matter only inside /…/ literals; in Python or Go strings, plain / works.

Frequently asked questions

Why does this reject localhost?

The (?:\.[\w-]+)+ group requires at least one dot in the hostname, which single-label hosts like localhost don't have. For dev tooling, use the scheme-optional variation and drop that group, or special-case localhost.

Should I use a regex or a URL parser?

For accepting/rejecting user input, a parser (new URL in JS, urllib.parse in Python) plus a scheme check is more correct. Regex wins when you're extracting URLs from a larger body of text, which parsers can't do.

Related patterns

Building something custom? The regex tester gives you live match highlighting for any pattern.