Regular Expressions
URL Validation
Programming
Web Development
Coding Tips

What is the best regular expression to check if a string is a valid URL?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

There is no single “best” regular expression for validating every valid URL. Real-world URLs are too varied, and once you account for schemes, ports, IPv6, query strings, encoded characters, and internationalized domains, a regex quickly becomes brittle. In practice, the best solution is usually to parse the URL with a real URL library and use regex only for small, pre-validation rules.

Why URL Validation Is Hard with Regex Alone

A URL can contain many optional pieces:

  • scheme such as http or https
  • host name, IPv4 address, or IPv6 address
  • optional port
  • optional path
  • optional query string
  • optional fragment

That variety makes fully correct regex validation difficult. A pattern that looks “good enough” often rejects valid URLs or accepts invalid ones.

For example, a regex might reject:

  • 'https://localhost:3000'
  • 'https://127.0.0.1:8080/api'
  • 'https://example.com/path?x=1&y=two'

Or it may accept strings that are not usable URLs at all.

Prefer a URL Parser in Application Code

In JavaScript, the built-in URL class is a much stronger validator than a hand-written regex:

javascript
1function isValidHttpUrl(value) {
2  try {
3    const url = new URL(value);
4    return url.protocol === "http:" || url.protocol === "https:";
5  } catch {
6    return false;
7  }
8}
9
10console.log(isValidHttpUrl("https://example.com"));
11console.log(isValidHttpUrl("not a url"));

That approach delegates the syntax rules to a real parser. You can then add business rules on top, such as restricting protocols or requiring a host.

A Python version looks similar:

python
1from urllib.parse import urlparse
2
3
4def is_valid_http_url(value: str) -> bool:
5    parsed = urlparse(value)
6    return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
7
8
9print(is_valid_http_url("https://example.com/docs"))
10print(is_valid_http_url("hello world"))

This is usually more reliable than writing a giant regex from scratch.

When Regex Is Still Useful

Regex is still fine when the rule is intentionally narrow. For example, maybe your form should allow only http and https URLs that start with a plausible scheme:

regex
^https?:\/\/\S+$

This is not a full validator. It is a coarse filter that says:

  • string must start with http:// or https://
  • the rest cannot contain whitespace

In JavaScript:

javascript
1const basicUrlPattern = /^https?:\/\/\S+$/;
2
3console.log(basicUrlPattern.test("https://example.com/path"));
4console.log(basicUrlPattern.test("ftp://example.com"));
5console.log(basicUrlPattern.test("https://bad url.com"));

That kind of regex is maintainable because its goal is limited and explicit.

Combine Parsing with Business Rules

The strongest pattern is usually parser first, business rules second. For example, if you want only HTTPS URLs from your company domain:

javascript
1function isAllowedUrl(value) {
2  try {
3    const url = new URL(value);
4    return url.protocol === "https:" && url.hostname.endsWith("example.com");
5  } catch {
6    return false;
7  }
8}

This is much clearer than trying to encode every rule into one complicated regex.

What About Relative URLs

Some applications need to accept relative paths such as /docs/setup or ../images/logo.png. A strict absolute-URL regex would reject those even though they are perfectly valid in context.

That is another reason “best regex” is the wrong framing. Validation rules depend on what your application actually accepts.

Common Pitfalls

The most common mistake is believing a huge regex equals correctness. In reality, giant patterns are difficult to maintain and often still miss edge cases.

Another pitfall is confusing URL validation with business validation. A URL can be syntactically valid and still be unacceptable because it uses the wrong scheme, wrong host, or wrong environment.

Developers also forget about localhost, IP addresses, and internal URLs. A regex tuned only for public domains often rejects values that are valid in development or enterprise settings.

Finally, parser-based validation should still be wrapped in business logic. Just because a parser accepts a URL does not mean your application should trust or use it automatically.

Summary

  • There is no single best regex for all valid URLs.
  • Use a real URL parser when you need reliable validation.
  • Use regex only for narrow, intentional pre-checks such as “must start with http or https.”
  • Separate syntax validation from business rules such as allowed schemes or domains.
  • Prefer maintainable validation logic over giant one-line regex patterns.

Course illustration
Course illustration

All Rights Reserved.