Regex for a URL
A practical URL pattern, with the parts that are easy to get subtly wrong called out.
/^https?:\/\/[\w\-]+(\.[\w\-]+)+(\/[\w\-._~:/?#[\]@!$&'()*+,;=]*)?$/
Match a whole string consisting of "h", then "t", then "t", then "p", then optionally "s", then ":", then "/", then "/", then one or more of a word character (letter, digit, or underscore) or "-", then one or more of (".", then one or more of a word character (letter, digit, or underscore) or "-"), then optionally ("/", then zero or more of a word character (letter, digit, or underscore), "-", ".", "_", "~", ":", "/", "?", "#", "[", "]", "@", "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", or "=").
What to check
Note
Anchors match string ends, not line ends
Without the m flag, ^ and $ match only the very start and end of the input — not the start and end of each line. On multi-line input this is often not what was intended.
Fix: Add the m flag if the pattern should apply per line.
Step by step
^Anchor to the start of the input.
hMatch "h".
tMatch "t".
tMatch "t".
pMatch "p".
s?Match optionally "s".
:Match ":".
/Match "/".
/Match "/".
[\w\-]+Match one or more of a word character (letter, digit, or underscore) or "-".
(\.[\w\-]+)+Match one or more of (".", then one or more of a word character (letter, digit, or underscore) or "-").
(\/[\w\-._~:/?#[\]@!$&'()*+,;=]*)?Match optionally ("/", then zero or more of a word character (letter, digit, or underscore), "-", ".", "_", "~", ":", "/", "?", "#", "[", "]", "@", "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", or "=").
$Anchor to the end of the input.
Details
- Capture groups
- 2
- Flags
- None set
Check your own pattern
Paste one on the home page, or call the API or MCP server. This page is also available as markdown.