用于验证DNS标签的正则表达式(主机名) [英] Regular Expression for validating DNS label ( host name)

查看:2404
本文介绍了用于验证DNS标签的正则表达式(主机名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想仅使用regualr表达式来验证主机名。

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

主机名(或DNS标语中的标签)传统上由RFC 952和RFC 1123定义,可能由以下有效字符组成。

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.

列表项目


  • A到Z;大写字符

  • a到z;小写字符

  • 0到9;数字字符0到9

  • - ;破折号

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

规则说:


  • 主机名(标签)可以用字母或数字开始或结尾

  • 主机名(标签)不得以 - (破折号)开头或结尾

  • 主机名(标签)不得包含所有数值

  • 主机名(标签)最多可以有63个字符

  • 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 ?

推荐答案

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

我使用Python编写的以下测试表来验证它是否正常工作:

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

这篇关于用于验证DNS标签的正则表达式(主机名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆