Regex for Subdomain Extraction
Regex Pattern
^(?:https?:\/\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}Extracts the subdomain from a URL or domain name
Quick Answer
The regex pattern for subdomain extraction is `^(?:https?:\/\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}`. Extracts the subdomain from a URL or domain name. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| api.example.com | ✓ Matches |
| https://blog.example.co.uk | ✓ Matches |
| cdn.static.example.com | ✓ Matches |
| example.com | ✗ No match |
| http://example.com | ✗ No match |
| localhost | ✗ No match |
Code Examples
javascript
const regex = /^(?:https?:\\/\\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/;
const isValid = regex.test(value);python
import re
pattern = r'^(?:https?:\/\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}'
if re.match(pattern, value):
print("valid")ruby
pattern = /^(?:https?:\/\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/
if value =~ pattern
puts "valid"
endphp
if (preg_match('/^(?:https?:\\/\\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\.(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/', $value)) {
echo "valid";
}java
String pattern = "^(?:https?:\\/\\/)?([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)\\.(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}";
boolean isValid = value.matches(pattern);Frequently Asked Questions
Related Regex Patterns
Protocol Detection
Detects and captures the protocol from a URL
Port Number
Extracts port number from a URL or host string
Query Parameter
Extracts key-value pairs from URL query strings
HTTP vs HTTPS URL
Matches HTTP or HTTPS URLs and captures the protocol
Data URL
Matches data: URL scheme with optional MIME type and base64 encoding
WebSocket URL
WebSocket URL starting with ws:// or wss://