Regular expression to match DNS hostname or IP Address?

后端 未结 21 2543
长发绾君心
长发绾君心 2020-11-21 07:25

Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?

It\'s easy to write one that works 95% of the time, but I\'m hoping

21条回答
  •  暖寄归人
    2020-11-21 07:45

    The hostname regex of smink does not observe the limitation on the length of individual labels within a hostname. Each label within a valid hostname may be no more than 63 octets long.

    ValidHostnameRegex="^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\
    (\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$"

    Note that the backslash at the end of the first line (above) is Unix shell syntax for splitting the long line. It's not a part of the regular expression itself.

    Here's just the regular expression alone on a single line:

    ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$

    You should also check separately that the total length of the hostname must not exceed 255 characters. For more information, please consult RFC-952 and RFC-1123.

提交回复
热议问题