普通EX pression验证FQDN在C#和Javascript普通、EX、pression、FQDN

2023-09-03 21:49:37 作者:永远有多远

什么是正确的常规EX pression验证FQDN在C#和Javascript? 我一直在寻找各地,我觉得不同的规格。哪一个是正确的。

What is the right regular expression to validate FQDN in C# and Javascript? I have been searching all around and I find different specifications. Which one is correct.

几个例子,我发现:

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

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

    3. \b((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b 

   (Regular Expression cook book)

请帮忙

推荐答案

一般情况下,普通防爆pressions食谱是一个很好的信息来源,由两位正则表达式的专家,所以你应该开始出现。该解决方案概述有不太适应您的需求,但(它不验证整个字符串,但匹配的子串,它不会检查字符串的总长度),因此我们可以通过修改它一点:

Generally, the Regular Expressions cookbook is a good source of information, written by two regex experts, so you should be starting there. The solution outlined there is not quite adapted to your needs yet (it doesn't validate an entire string but matches substrings, and it doesn't check for the overall length of the string), so we can modify it a little:

/^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}$/i

说明:

^                      # Start of string
(?=.{1,254}$)          # Assert length of string: 1-254 characters
(                      # Match the following group (domain name segment):
 (?=[a-z0-9-]{1,63}\.) # Assert length of group: 1-63 characters
 (xn--+)?              # Allow punycode notation (at least two dashes)
 [a-z0-9]+             # Match letters/digits
 (-[a-z0-9]+)*         # optionally followed by dash-separated letters/digits
 \.                    # followed by a dot.
)+                     # Repeat this as needed (at least one match is required)
[a-z]{2,63}            # Match the TLD (at least 2 characters)
$                      # End of string