简体   繁体   English

使用正则表达式验证C#中的FQDN

[英]Validate FQDN in C# using regex

I wrote the following pattern in C# to validate a FQDN received from a user: 我在C#中编写了以下模式,以验证从用户收到的FQDN:

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

I want to allow the user to enter the following FQDN: 我想允许用户输入以下FQDN:

<name>.<letter><digit>

such as "aa.a1". 例如“ aa.a1”。 For "aa.a1" my regex detects the FQDN as invalid, and for "aa.1a" it detects it as valid. 对于“ aa.a1”,我的正则表达式将FQDN检测为无效,而对于“ aa.1a”,则将其检测为有效。 Does anyone know why? 有人知道为什么吗?

Instead of using a RegEx, you can load the string into a Uri and use the different methods and properties to figure out if it is a FQDN. 您可以将字符串加载到Uri并使用不同的方法和属性来确定它是否为FQDN,而不是使用RegEx。

Uri uri = new Undri(myFQDN);
string host = uri.Host;
bool isAbsolute = uri.IsAbsoluteUri;

I'm not going to even try to decode that huge regex, use the Uri.IsWellFormedUriString method instead. 我什至不打算尝试解码巨大的正则表达式,而是使用Uri.IsWellFormedUriString方法。 That already does what you are looking for. 这已经可以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM