开发者

Looking for regex/code for hostname/machine name validation

Looking for hostname validation regex.

Regular expression to match DNS hostname or IP Address?

In that link gentlemen prop开发者_如何学编程ose a decent regex. I have a few problems/questions with that:

  • On windows computers/networks names like 1abcd are allowed (verified on our local network)
  • In the proposed regex the dot might appear only once. I'd assume that abc.def.gh is a valid hostname as well, isn't it.

Strange, but also couldn't find any .NET class that can validate hostname string (is it the situation?). Any advice will be highly appreciated.

Update: for any class/method proposal - please advice something that will work both in .NET/C# and SilverLight.


In the proposed regex the dot might appear only once. I'd assume that abc.def.gh is a valid hostname as well, isn't it.

The dot MAY appear more than once. Test the regular expression here and you will see that it matches.

Relevant fragment of the regular expression (first part is):

([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*

On windows computers/networks names like 1abcd are allowed (verified on our local network)

From wikipedia:

The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits.

I referred to RFC 952. I will try to update the regular expression for hostnames to be compliant with RFC 1123.


Is Uri.CheckHostName a method that can help you ? If the hostname is not recognize, the result will be "Unknown".


(?i)(?=.{5,20}$)^(([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])\.)*([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])$

Explanation:

(?i) - Ignore case

(?=.{5,20}$) - Limit the string length within 5 to 20 characters.

^(([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])\.)*([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])$ - Accepts any alphabets and numeric along with hyphen and dot

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜