breakitdown

Regex for an http or https URL

Answer

^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$ with the i flag matches http:// or https://, a host, and an optional path, query or fragment, with no spaces anywhere. For real validation in JavaScript, parse with new URL(s) and check that protocol is http: or https:.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. ^Start of the stringanchor
  2. httpThe text "http" literally (any case, because of the i flag)literal
  3. sThe character 's'literal
  4. ?Repeat it optionally (zero or one time)quantifier
  5. :\/\/The text "://" literally (any case, because of the i flag)literal
  6. [^\s/?#]Any one character except a whitespace character (space, tab, line break and other Unicode spaces), '/', '?' and '#'character class
  7. +Repeat the class one or more times, as many as possible (greedy)quantifier
  8. (?:…)Non-capturing group: groups without rememberinggroup
  9. [/?#]One character: '/', '?' or '#'character class
  10. \SAny character that is not whitespacecharacter type
  11. *Repeat it zero or more times, as many as possible (greedy)quantifier
  12. ?Then repeat the whole group optionally (zero or one time)quantifier
  13. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
https://example.com✓ match
http://localhost:8080/path?q=1#top✓ match
HTTPS://EXAMPLE.COM/✓ match
https://[2001:db8::1]/✓ match
ftp://example.com✗ no match
https://✗ no match
https://exa mple.com✗ no match
example.com✗ no match
https://-.-✓ match
https://user:pass@example.com✓ match

Try your own text

One string per line: each line is tested on its own (the m flag is added here).

How it works

The pattern splits a URL where the URL standard does. After the scheme and // comes the authority: everything up to the first /, ? or #. That is [^\s/?#]+. Whatever follows must start with one of those three characters, and the rest is any run of non-space characters.

It does not check that the host is a real domain or IP address. https://-.- passes. Checking hostnames properly means handling IPv6 literals in brackets, ports, user info (user:pass@host), and Unicode domains. A parser already does all of that, so use one when correctness matters and keep the regex for quick filtering, such as finding links in text.

Variants

Gotchas

Related explainers

← Explain any regular expression