Regex
URL Regex: How to Match and Validate a URL
Published 2026-08-15 · 7 min read
TL;DR: Match most URLs with ^https?://[^\s]+$, and for real validation prefer the URL API with a restricted scheme list over a regex that cannot catch structural errors.
URLs look like the kind of thing a regex should handle, and two different jobs hide under that idea. Matching a URL inside a paragraph of text, and validating that a submitted input is a legitimate URL, need different tools. A regex handles the first; for the second, the browser URL API or a library is usually the better tool, because it rejects structural errors a pattern cannot see. The official grammar lives in the WHATWG URL standard.
What are the parts of a URL?
- Scheme: the protocol, such as https or ftp, followed by a colon.
- Authority: usually a host and optional port, such as example.com:8080.
- Path: the resource, such as /docs/guide.
- Query: parameters after a question mark, such as ?page=2.
- Fragment: an anchor after a hash, such as #section-3.
Each part has its own rules, and the ones that trip up regexes are the port, which is optional, the query, which can contain almost anything except spaces and control characters, and the fragment, which is never sent to the server. A full pattern must account for all of them being optional except the scheme.
What is a simple URL regex?
For matching links in plain text, a short pattern covers almost everything real:
\bhttps?://[^\s<>"'\[\]{}]+\bIt looks for a word boundary, an http or https scheme, then everything up to whitespace or one of the punctuation characters that usually ends a sentence. It will match https://example.com/page?q=1 in a sentence without swallowing the closing period. The regex tester is the fastest way to tune this against your own text samples.
What is a more complete URL regex?
If you insist on a single pattern, the widely used one below accepts optional ports, userinfo, query and fragment:
^(https?):\/\/[^\s\/$.?#].[^\s]*$Even this accepts https://: as a valid URL, because the pattern only checks character classes, not structure. That is the fundamental limit of regex for URLs: the grammar has ordering rules a pattern cannot encode cleanly. When the input matters, parse it instead.
When should you use a parser instead of a regex?
For a form field that accepts one URL, parse it and check the result. In JavaScript, new URL(value) throws on malformed input, and after parsing you can require the protocol to be http or https and the host to be non-empty. A parser also normalizes the value, handles international domains and rejects schemes you did not allow. In Python, urllib.parse.urlsplit gives the same parts to inspect.
function isValidHttpUrl(s) {
try {
const u = new URL(s);
return (u.protocol === 'http:' || u.protocol === 'https:') && u.hostname.length > 0;
} catch {
return false;
}
}How do you prevent javascript: injection?
The classic attack is a value such as javascript:alert(1) that a loose regex accepts and the browser then executes. Restricting the scheme list to http and https, whether in a regex or in the parser check, blocks it. Never build a link from user input without that scheme check, because href attributes will run javascript: URLs when clicked.
How do you match URLs without a trailing dot?
When text ends with a sentence, the trailing period is not part of the URL. The boundary class in the simple pattern stops before characters like the period and comma, but a URL that ends with a path such as /about. still risks losing its final dot. The reliable fix is to strip trailing punctuation after a match, then verify with a parser. Patterns that try to decide dot-by-dot get long and still guess wrong.
How do you test a URL pattern?
Collect a small corpus: normal links, links at the end of sentences, a localhost address, a port, a query with an ampersand, and one clearly broken string such as https://. Run the regex tester against all of them, and decide which cases are acceptable to let through or reject. The same method applies to the email regex guide: pick the trade-offs deliberately instead of inheriting them from a copied pattern.
Related Tools
Related Guides
Regular Expressions Guide: How Regex Works with Examples
Learn regular expressions from scratch: literals, metacharacters, character classes, quantifiers, anchors, groups and flags, with examples you can test online.
Regex Cheat Sheet: Every Metacharacter Explained
A compact regex cheat sheet: anchors, character classes, quantifiers, groups, alternation and flags, with the meaning and an example for every common token.
Email Regex: How to Validate an Email Address
A practical email regex, why the full RFC 5322 pattern is a trap, and how to validate email in HTML5, JavaScript and Python without over-engineering.
Frequently Asked Questions
What is the best regex to validate a URL?
For practical validation the simplest approach is not a regex at all: parse with the URL API or a library and check that the protocol is http or https and that a host exists. Regex is better for matching URLs inside a block of text.
Why is a simple URL regex not enough?
A pattern such as ^https?://[^\s]+$ accepts structurally broken URLs like https:// or https://:bad, because it only checks the shape loosely. A parser rejects those, which is why validation should use the parser and matching should use the regex.
Should the regex allow ftp:// or other schemes?
Only if you intend to accept them. Unrestricted schemes let an attacker submit javascript: or file: URLs, so when you validate for a form, restrict the scheme list to http and https.
How do you match URLs inside free text?
Use a pattern with word boundaries and character classes that exclude punctuation, such as \bhttps?://[^\s<>\[\]{}]+\b. The full URL grammar is complex, so most parsers in text (such as Markdown linkifiers) handle it with heuristics plus a boundary check.
Do URL regexes work with international domains?
A regex sees the punycode form such as xn--fsqu00a.xn--0zwm56d, or the raw unicode form if you allow those characters. In practice you do not validate international domains with a regex; the URL API or the domain parser handles the conversion.