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]*)?$/iMatches
https://regexkit.devhttp://sub.example.co.uk:8080/path?q=1#tophttps://example.com/a_b-c
Doesn't match
example.comftp://example.comhttps://localhosthttps:// 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 falsePython
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