URL and URI Matching
What You'll Learn
You'll learn how to construct regex patterns to validate URLs with protocols, domains, paths, and query parameters.
Understanding URL Components
A URL has several parts that you need to validate: the protocol (like http or https), the domain name, optional ports, paths, and query parameters. Think of a URL like a postal address—each component has its own format rules, and your regex must check them all.
A typical URL looks like: https://example.com:8080/path/to/resource?key=value&name=test
Building a URL Pattern
Here's how to construct a pattern piece by piece:
String urlPattern =
"^(https?)://" + // Protocol (http or https)
"([a-zA-Z0-9.-]+)" + // Domain name
"(:[0-9]{1,5})?" + // Optional port
"(/[a-zA-Z0-9._~:/?#\\[\\]@!$&'()*+,;=-]*)?" + // Optional path
"(\\?[a-zA-Z0-9._~:/?#\\[\\]@!$&'()*+,;=-]*)?$"; // Optional query
Pattern pattern = Pattern.compile(urlPattern);
Matcher matcher = pattern.matcher("https://example.com/path?key=value");
if (matcher.matches()) {
String protocol = matcher.group(1); // "https"
String domain = matcher.group(2); // "example.com"
String port = matcher.group(3); // null (not present)
String path = matcher.group(4); // "/path"
String query = matcher.group(5); // "?key=value"
}
Key Components Explained
- Protocol:
(https?)matches "http" or "https" - Domain:
[a-zA-Z0-9.-]+allows letters, digits, dots, and hyphens - Port:
:[0-9]{1,5}is optional (?) and matches 1-5 digits - Path and Query: Character classes include URL-safe characters
For simpler validation, you might start with basic patterns and refine them based on your specific needs.
Key Takeaway: URL regex patterns combine multiple capturing groups to validate protocol, domain, port, path, and query string components, allowing you to both validate URL format and extract individual parts for processing.