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

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

问题描述

我想仅使用正则表达式来验证主机名.

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
  • - ;破折号

规则说:

  • 主机名(标签)可以以字母或数字开头或结尾
  • 主机名(标签)不得以-"(破折号)开头或结尾
  • 主机名(标签)不得包含所有数值
  • 主机名(标签)最多可包含 63 个字符

您将如何编写正则表达式来验证主机名?

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天全站免登陆