Regex for Validating a URL

A basic pattern for matching http/https URLs.

Published October 10, 2026

A simple regex for http and https URLs checks the scheme, a host with a dot and an optional path or query.

How the pattern works

Breaking the pattern down: https?:// = http or https; [^\s/$.?#] = first host character; [^\s]*\.[^\s]{2,} = rest of host with a dot and TLD.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/^https?://[^\s/$.?#][^\s]*\.[^\s]{2,}$/
✓ 'https://example.com'
✓ 'http://sub.example.co.uk/path?x=1'
✗ 'example.com'
✗ 'ftp://example.com'

Practical examples

The pattern

const re = /^https?://[^\s/$.?#][^\s]*\.[^\s]{2,}$/

Test it

const re = /^https?://[^\s/$.?#][^\s]*\.[^\s]{2,}$/
re.test('https://example.com')   // true
re.test('http://sub.example.co.uk/path?x=1')   // true
re.test('example.com')   // false
re.test('ftp://example.com')   // false

In Python

import re
re.search(r'^https?://[^\s/$.?#][^\s]*\.[^\s]{2,}$', text)

Common mistakes

  • Using regex when new URL() would validate correctly.
  • Rejecting internationalised domains.
  • Accepting javascript: URLs.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

Better way in JS?

new URL(str) in a try/catch.

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles