URL regex

A regex to match or validate http/https URLs with optional port, path, query and fragment, plus when to use the URL constructor instead.

Pattern
/^https?:\/\/(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?::\d{2,5})?(?:[\/?#][^\s]*)?$/i

Matches

  • https://regexkit.dev
  • http://sub.example.co.uk:8080/path?q=1#top
  • https://example.com/a_b-c

Doesn't match

  • example.com
  • ftp://example.com
  • https://localhost
  • https:// example.com

Alternative: Find URLs inside text (no anchors, use with g)

https?:\/\/[^\s<>"')\]]+

Notes

  • For validation in JavaScript, new URL(value) is more accurate than any regex — wrap it in try/catch and check url.protocol.
  • This pattern requires a dot in the host, so localhost and bare IPs fail on purpose. Adjust if you need them.
  • The "find in text" version stops at whitespace, quotes and closing brackets so trailing punctuation in prose isn't swallowed.

Code

JavaScript

const re = /^https?:\/\/(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?::\d{2,5})?(?:[\/?#][^\s]*)?$/i;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'https?://(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?::\d{2,5})?(?:[/?#][^\s]*)?', value, re.I))

Try it on your own input

The live tester adds the g and m flags so every line is checked separately.

Questions

Why does my URL regex match the trailing full stop?

Because a dot is legal in a URL path. Exclude common trailing punctuation or trim it after matching.

More patterns

Email regexPhone number regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regexPassword regex