乐闻世界logo
搜索文章和话题

Regular Expression for validating DNS label ( host name)

1个答案

1

When validating DNS labels (hostnames), we must adhere to specific rules. According to RFC 1035, DNS labels (i.e., each segment separated by a dot) must satisfy the following conditions:

  1. The label length must be between 1 and 63 characters.
  2. The label can only contain letters (a-z, A-Z), digits (0-9), and hyphens (-).
  3. The label cannot start or end with a hyphen.
  4. The label cannot consist entirely of digits (but may contain digits).

Based on these rules, we can construct a regular expression to validate DNS labels. Here is an example:

regex
^(?!-)(?!.*-$)(?!.*\d+$)[a-zA-Z\d-]{1,63}$

Explanation:

  • ^ and $ denote the start and end of the string, respectively, ensuring the entire string meets the conditions.
  • (?!-) ensures the string does not begin with a hyphen.
  • (?!.*-$) ensures the string does not end with a hyphen.
  • (?!.*\d+$) ensures the string is not entirely numeric.
  • [a-zA-Z\d-]{1,63} ensures the string contains 1 to 63 allowed characters (letters, digits, hyphens).

Examples: Suppose we need to validate the following labels for DNS compliance:

  • example - valid
  • ex-ample - valid
  • -example - invalid, as it begins with a hyphen
  • example- - invalid, as it ends with a hyphen
  • 123456 - invalid, as it consists entirely of digits

This regular expression correctly validates all the above examples, ensuring compliance with DNS label rules. Such a validation mechanism can be applied in network programming and system configuration to ensure user input or generated hostnames conform to standards.

2024年7月12日 16:42 回复

你的答案