Regex for URLs

A deliberately simple regular expression for web addresses, a pattern for finding links in running text, and why the URL parser built into your language should have the final say.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

/^https?:\/\/[^\s\/?#]+(?:[\/?#]\S*)?$/i

This pattern answers one question: does the text look like an absolute http or https link with something where the host should be? It is meant for a form field such as "your website", where a missing https:// or a stray space is the usual mistake.

The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.

How it works, token by token

PartMeaning
^Start of the string.
https?http with an optional s. The i flag makes it case-insensitive, as URL schemes are.
:\/\/The literal ://, with the slashes escaped for JavaScript's /…/ syntax.
[^\s\/?#]+The authority: one or more characters that are not whitespace, /, ? or #. That covers the host name and any user name or port.
(?:[\/?#]\S*)?Optionally, a path, query or fragment: one of /, ? or #, then any run of non-whitespace characters.
$End of the string.

What it matches and what it rejects

InputResultWhy
https://example.commatchesA bare host.
http://localhost:8080/admin?tab=users#topmatchesPort, path, query and fragment.
HTTPS://EXAMPLE.COM/AmatchesCase-insensitive.
https://example.com?q=1matchesA query straight after the host.
http://[::1]:8080/matchesAn IPv6 literal in brackets.
http://999.999.999.999/matchesAccepted, but not a valid address: see the parser below.
example.comrejectedNo scheme.
www.example.comrejectedStill no scheme.
ftp://example.com/rejectedOnly http and https.
https://rejectedNo host.
https:// example.comrejectedA space after the scheme.
https://example.com/a brejectedA space in the path: it must be encoded as %20.
//example.com/xrejectedA scheme-relative URL.

Let the URL parser decide

The rules for URLs are long: RFC 3986 defines the generic syntax, and browsers follow the WHATWG URL Standard, which also covers international domain names, IPv4 numbers in odd notations and many forms of error recovery. Every attempt to put that into one regex is either wrong or unreadable. Use the regex for a quick shape check, then give the text to the parser your language already has:

function isHttpUrl(text) {
  try {
    const u = new URL(text);
    return u.protocol === 'https:' || u.protocol === 'http:';
  } catch {
    return false;
  }
}

console.log(isHttpUrl('https://example.com/a?b=1'));  // → true
console.log(isHttpUrl('https://exa mple.com'));       // → false
console.log(isHttpUrl('http://999.1.1.1/'));          // → false
console.log(isHttpUrl('ftp://example.com/'));         // → false
console.log(new URL('HTTPS://Example.COM/a').href);   // → https://example.com/a

Python's urllib.parse.urlsplit splits a URL into parts but does very little checking, so test the parts it returns:

from urllib.parse import urlsplit

parts = urlsplit('https://user@example.com:8080/a?b=1#top')
print(parts.scheme, parts.hostname, parts.port, parts.path)  # → https example.com 8080 /a
print(urlsplit('https://exa mple.com').netloc)                # → exa mple.com   it splits, it does not validate

Finding links in text

To pick links out of a paragraph, drop the anchors and stop at whitespace, angle brackets and quotes. The catch is punctuation at the end of a sentence:

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

Searching this text:

Docs: https://example.com/guide. Or see (https://example.org/a?b=1).

finds 2 matches:

1. https://example.com/guide.
2. https://example.org/a?b=1).

Requiring the last character to be something other than common punctuation fixes the usual cases:

/https?:\/\/[^\s<>"]*[^\s<>".,;:!?)']/

Searching this text:

Docs: https://example.com/guide. Or see (https://example.org/a?b=1).

finds 2 matches:

1. https://example.com/guide
2. https://example.org/a?b=1

It still cuts a link that really ends in ), as some Wikipedia addresses do. Linkify libraries handle that by balancing brackets; for a comment box or a chat message, the simple version is usually enough.

Never check a redirect target with a regex

A common bug is to allow redirects or callbacks when the URL "starts with" your domain:

/^https:\/\/example\.com/
InputResultWhy
https://example.com/loginmatchesIntended.
https://example.com.evil.net/matchesAlso matches: nothing says where the host ends.
https://example.com@evil.net/matchesAlso matches, and the real host here is evil.net. example.com is only a user name.
https://evil.net/?next=https://example.comrejectedRejected only because of the ^.

Parse the URL and compare its host name with an exact list instead:

const allowed = new Set(['example.com', 'www.example.com']);
const safe = (text) => { try { return allowed.has(new URL(text).hostname); } catch { return false; } };
console.log(safe('https://example.com/login'));      // → true
console.log(safe('https://example.com.evil.net/'));  // → false
console.log(new URL('https://example.com@evil.net/').hostname);  // → evil.net

In JavaScript, Python, PHP and C#

JavaScript

const re = /^https?:\/\/[^\s\/?#]+(?:[\/?#]\S*)?$/i;
console.log(re.test('https://example.com')); // → true
console.log(re.test('example.com')); // → false

Python

import re

pattern = re.compile(r'https?://[^\s/?#]+(?:[/?#]\S*)?', re.IGNORECASE)
print(bool(pattern.fullmatch('https://example.com')))  # → True
print(bool(pattern.fullmatch('example.com')))  # → False

PHP

<?php
$pattern = '/^https?:\/\/[^\s\/?#]+(?:[\/?#]\S*)?$/iD';
echo preg_match($pattern, 'https://example.com'), "\n"; // → 1
echo preg_match($pattern, 'example.com'), "\n"; // → 0

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^https?://[^\s/?#]+(?:[/?#]\S*)?\z", RegexOptions.IgnoreCase);
Console.WriteLine(pattern.IsMatch("https://example.com")); // → True
Console.WriteLine(pattern.IsMatch("example.com")); // → False

Each version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

What is a good regex to validate a URL?

For a form field, ^https?:\/\/[^\s\/?#]+(?:[\/?#]\S*)?$ with the i flag checks for an http or https scheme, a host and no spaces. For anything security-related, parse the URL with new URL() or your language's parser and check its parts.

How do I match URLs without http or https?

Make the scheme optional with (?:https?:\/\/)? and accept that www.example.com and example.com then both match, as will many ordinary words with a dot in them, such as file.txt. Adding https:// for the user before parsing is usually the better approach.

Why does my URL regex include the full stop at the end of a sentence?

Because a full stop is a legal URL character. Require the last character to be something other than punctuation, as in the second pattern on this page.