在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)
请帮忙
答案 0 :(得分: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