Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for validating DNS label ( host name)

I would like to validate a hostname using only regualr expression.

Host Names (or 'labels' in DNS jargon) were traditionally defined by RFC 952 and RFC 1123 and may be composed of the following valid characters.

List item

  • A to Z ; upper case characters
  • a to z ; lower case characters
  • 0 to 9 ; numeric characters 0 to 9
  • - ; dash

The rules say:

  • A host name (label) can start or end with a letter or a number
  • A host name (label) MUST NOT start or end with a '-' (dash)
  • A host name (label) MUST NOT consist of all numeric values
  • A host name (label) can be up to 63 characters

How would you write Regular Expression to validate hostname ?

like image 485
Rwahyudi Avatar asked Jan 14 '10 09:01

Rwahyudi


People also ask

How do I find the regex for a domain name?

[A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long. (? <!

How do you validate expressions in regex?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.


3 Answers

^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,63}(?<!-)$

I used the following testbed written in Python to verify that it works correctly:

tests = [
    ('01010', False),
    ('abc', True),
    ('A0c', True),
    ('A0c-', False),
    ('-A0c', False),
    ('A-0c', True),
    ('o123456701234567012345670123456701234567012345670123456701234567', False),
    ('o12345670123456701234567012345670123456701234567012345670123456', True),
    ('', True),
    ('a', True),
    ('0--0', True),
]

import re
regex = re.compile('^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,63}(?<!-)$')
for (s, expected) in tests:
    is_match = regex.match(s) is not None
    print is_match == expected
like image 95
Mark Byers Avatar answered Sep 20 '22 22:09

Mark Byers


Javascript regex based on Marks answer:

pattern = /^(?![0-9]+$)(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$/g;
like image 40
Tom Lime Avatar answered Sep 19 '22 22:09

Tom Lime


The k8s API responds with the regex that it uses to validate e.g. an RFC 1123-compliant string:

(⎈ minikube:default)➜  cloud-app git:(mc/72-org-ns-names) ✗ k create ns not-valid1234234$%
The Namespace "not-valid1234234$%" is invalid: metadata.name: 
Invalid value: "not-valid1234234$%": a lowercase RFC 1123 label must consist of lower case 
alphanumeric characters or '-', and must start and end with an alphanumeric character 
(e.g. 'my-name',  or '123-abc', regex used for validation is
 '[a-z0-9]([-a-z0-9]*[a-z0-9])?')
like image 22
mecampbellsoup Avatar answered Sep 22 '22 22:09

mecampbellsoup