The Hostname Regex

后端 未结 5 985
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 02:36

I\'m looking for the regex to validate hostnames. It must completely conform to the standard. Right now, I have

^[0-9a-z]([0-9a-z\\-]{0,61}[0-9a-z])?(\\

5条回答
  •  生来不讨喜
    2020-12-09 03:13

    Your answer was relatively close.

    But see

    • RFC 2396 Section 3.2.2
    • JaredPar's reference to this answer is referring to Regexp/Common/URI/RFC2396.pm source.

    For a hostname RE, that perl module produces

    (?:(?:(?:(?:[a-zA-Z0-9][-a-zA-Z0-9]*)?[a-zA-Z0-9])[.])*(?:[a-zA-Z][-a-zA-Z0-9]*[a-zA-Z0-9]|[a-zA-Z])[.]?)
    

    I would modify to be more accurate as:

    (?:(?:(?:(?:[a-zA-Z0-9][-a-zA-Z0-9]{0,61})?[a-zA-Z0-9])[.])*(?:[a-zA-Z][-a-zA-Z0-9]{0,61}[a-zA-Z0-9]|[a-zA-Z])[.]?)
    

    Optionally anchoring the ends with ^$ to ONLY match hostnames.

    I don't think a single RE can accomplish an full validation because, according to Wikipedia, there is a 255 character length restriction which i don't think can be included within that same RE, at least not without a ton of changes, but it's easy enough to just check the length <= 255 before running the RE.

提交回复
热议问题