Validate a hostname string

后端 未结 10 1526
生来不讨喜
生来不讨喜 2020-12-04 13:24

Following up to Regular expression to match hostname or IP Address? and using Restrictions on valid host names as a reference, what is the most readable, concise way to matc

10条回答
  •  遥遥无期
    2020-12-04 13:55

    Complimentary to the @TimPietzcker answer. Underscore is a valid hostname character (but not for domain name) . While double dash is commonly found for IDN punycode domain(e.g. xn--). Port number should be stripped. This is the cleanup of the code.

    import re
    def is_valid_hostname(hostname):
        if len(hostname) > 255:
            return False
        hostname = hostname.rstrip(".")
        allowed = re.compile("(?!-)[A-Z\d\-\_]{1,63}(?

提交回复
热议问题