Hostname (Single Label) Regex Pattern

Validates a single DNS hostname label (no dots, 1-63 characters).

Pattern
^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$

Tested examples

localhost
my-server
web01
-invalid
host.name
toolooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong

Test it live

Live Regex TesterJS
0 matches
/
/g
localhost
my-server
web01

Use it in your language

Use it in
// JavaScript / Node.js
const regex = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
const value = "localhost";
const isMatch = regex.test(value);
console.log(isMatch); // true / false

// Extract all matches
const matches = value.match(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/g) || [];

Tags

Frequently asked questions

How do I use the Hostname (Single Label) regex pattern in JavaScript?
Wrap the pattern in slashes: const re = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/; — then call re.test(value) to check a single value, or value.match(re) to find matches. The "Use it in" snippets above give you the exact code for 9 languages.
Is this hostname (single label) regex production-ready?
Yes — every pattern in the library is tested against valid and invalid examples. Still, regex is one layer in a defense-in-depth strategy: pair it with server-side validation (e.g. Luhn for credit cards, mod-97 for IBAN, real DNS lookup for emails) for critical inputs.
Why does my pattern fail in another language?
Different regex engines (PCRE, Java, Python, Go's RE2) support slightly different syntax. The most common gotchas: lookbehinds (not in RE2), named groups syntax, and how backslashes need to be escaped inside string literals. The code snippets above already escape correctly for each language.
Can I edit this pattern and test it live?
Yes — use the live tester above. Type your test string and toggle flags (g, i, m, s, u, y) to see matches highlighted instantly, including capture groups.

Related patterns

See all Network

Browse the full library — 250 tested regex patterns across 16 categories.