Validate FQDN in C#

£可爱£侵袭症+ 提交于 2019-12-10 14:43:08

问题


Does anyone have a Regular Expression to validate legal FQDN?

Now, I use on this regex:

(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?!-)\.?)+(?:[a-zA-Z]{2,})$)

However this regex results in "aa.a" not being valid while "aa.aa" is valid.

Does anyone know why?


回答1:


Here's a shorter pattern:

(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)

As for why the pattern determines "aa.a" as invalid and "aa.aa" as valid, it's because of the {2,} - if you change the 2 to a 1 so that it's

(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{1,})$)

it should deem both "aa.a" and "aa.aa" as valid.

string pattern = @"(?=^.{1,254}$)(^(?:(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{1,})$)";
bool isMatch = Regex.IsMatch("aa.a", pattern);

isMatch is TRUE for me.




回答2:


I think this could also be an option especially if the FQDN will later be used along with System.Uri:

var isWellFormed = Uri.CheckHostName(stringToCheck).Equals(UriHostNameType.Dns);

Note that this code considers partially qualified domain names to be well formed.



来源:https://stackoverflow.com/questions/4912520/validate-fqdn-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!