Hostname (Single Label, RFC 1123)
Validate a single-label hostname per RFC 1123: 1–63 chars, letters/digits/hyphens, can't start or end with hyphen.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("^[a-zA-Z0-9](?:[a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?$", "");
const input = "web-01";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$")
input_text = "web-01"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$`)
input := `web-01`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$Raw source: ^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$
How it works
Examples
Input
web-01Matches
web-01
Input
host123Matches
host123
Input
-bad-startNo match
—Common use cases
- •Kubernetes pod and service name validation
- •DNS label sanity checking
- •Container hostname enforcement
- •Server provisioning input validation
Related patterns
Kubernetes Pod Name (RFC 1123)
IdentifiersValidate Kubernetes pod names per the RFC 1123 DNS label rules — lowercase, ≤63 chars, no leading/trailing hyphen.
Private IP Address (RFC 1918)
NetworkingMatch IPv4 addresses in the RFC 1918 private ranges: 10/8, 192.168/16, and 172.16/12.
MAC Address
NetworkingMatch 48-bit MAC addresses written with colon or hyphen separators (e.g. 00:1A:2B:3C:4D:5E).
Domain Name
NetworkingMatch fully-qualified domain names like example.com or api.sub.example.co.uk.