Pattern Breakdown
Understanding the regex pattern ^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$:
- ^ - Start of string
- $ - End of string
- ? - Optional (zero or one)
- [...] - Character class
- (...) - Capturing group
- {n,m} - Quantifier (n to m times)
Examples
| Input | Result | Explanation |
|---|---|---|
www |
✓ Match | Common subdomain |
api-v2 |
✓ Match | With hyphen |
-invalid |
✗ No Match | Starts with hyphen |
Code Examples
JavaScript
JavaScript
const pattern = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
const text = "www";
// Test if string matches
if (pattern.test(text)) {
console.log("Valid!");
}
// Extract matches
const matches = text.match(pattern);
console.log(matches);
Python
Python
import re
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$'
text = "www"
# Test if string matches
if re.match(pattern, text):
print("Valid!")
# Find all matches
matches = re.findall(pattern, text)
print(matches)
PHP
PHP
<?php
$pattern = '/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/';
$text = "www";
// Test if string matches
if (preg_match($pattern, $text)) {
echo "Valid!";
}
// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>
Java
Java
import java.util.regex.*;
String pattern = "^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$";
String text = "www";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.matches()) {
System.out.println("Valid!");
}
Use Cases
Common applications: Multi-tenant apps, DNS management
- Form validation and input sanitization
- Data extraction and parsing
- Search and replace operations
- API request/response validation
- Log file analysis
Frequently Asked Questions
What is the regex pattern for subdomain regex?
The regex pattern is: ^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$. Validate subdomain labels: alphanumeric, hyphens allowed (not at start/end).
How do I use the subdomain regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$'); or const regex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for subdomain regex?
Multi-tenant apps, DNS management
Related Regex Patterns
More Regex Tools
GetDevUtils offers a suite of developer tools including:
- Regex Tester - Test and debug regular expressions
- JSON Formatter - Format and validate JSON
- Base64 Encoder/Decoder - Encode and decode Base64
- URL Encoder/Decoder - Encode and decode URLs