2

在 C# 和 Javascript 中验证 FQDN 的正确正则表达式是什么?我一直在四处寻找,我发现了不同的规格。哪一个是正确的。

我发现的几个例子:

   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)

请帮忙

4

1 回答 1

3

一般来说,正则表达式食谱是一个很好的信息来源,由两位正则表达式专家编写,所以你应该从那里开始。那里概述的解决方案还不能完全适应您的需求(它不会验证整个字符串,但会匹配子字符串,并且不会检查字符串的总长度),因此我们可以对其进行一些修改:

/^(?=.{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
于 2013-08-02T08:21:31.567 回答