Regex Patterns

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

1

The Pattern

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.

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

Examples

Example

Basic URLs

Matches:
https://example.com
http://example.com/page
https://example.com:8080/path

Does not match:
ftp://example.com
example.com
https://
Example

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

Does not match:
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.