Regex Pattern Library

URL Pattern

Match HTTP and HTTPS URLs with optional port, path, query string, and fragment.

What Is This?

This regex pattern matches HTTP and HTTPS URLs including optional components like port numbers, URL path, query string parameters, and fragment identifiers. It is designed for extracting or validating web URLs in text content.

How to Use This Pattern

1

Pattern

https?:\/\/[\w.-]+(:\d+)?(\/[\w./%-]*)?(\?[\w&=.-]*)?(#[\w-]*)?

https?:\/\/[\w.-]+(:\d+)?(\/[\w./%-]*)?(\?[\w&=.-]*)?(#[\w-]*)?
2

Usage

The pattern matches strings starting with http:// or https:// followed by a domain, optional port (:3000), optional path with forward slashes, optional query string (?key=value), and optional fragment (#section). Percent-encoded characters (%20) are supported in paths.

3

Flags

Use the i flag for case-insensitive matching.

Examples

Basic URLs

Matches: https://example.com, http://example.com/page, https://example.com:8080/path. Non-matches: ftp://example.com, example.com, https://

URLs with query and fragment

Matches: https://example.com/page?q=search&lang=en, https://example.com/page#section1, https://example.com/path%20with%20spaces. Non-matches: https://, http:///path, https://example .com

Related Entries

More from this reference:

Frequently Asked Questions

Does this pattern match all valid URLs?

No. This pattern matches common HTTP/HTTPS URLs but does not cover FTP, mailto, file, or other protocol URLs. For comprehensive URL matching, consider using a URL parsing library.

Should I validate or sanitize URLs?

Always sanitize URLs in addition to validating them. Malicious URLs can pass regex validation. Use URL parsing libraries and allowlisting for production security.