正则表达式帮助 - 域未验证

Regex help - domain is not validating

我在验证域时遇到问题。我做错了什么?

        Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$");
        if (re.IsMatch(domain.Text))
//          if (Regex.IsMatch(domain.Text, @"^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$"))
            warningLabel.Text = "Domain format is invalid!";    // domain: " + domain.Text;

我用 Regex 检查器检查并得到 "your pattern matches but there were no (capturing (groups)) in it that matched anything in the subject string."

为什么我没有收到有关无效字符的错误消息?

谢谢。

你的正则表达式基本上是正确的(但见下文link),这个测试方法证实了这一点:

public static void Test()
        {
            Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$");
            var m=re.Match("test.com");
            Console.WriteLine(m.Groups[0].Value);
            m=   re.Match("more-messy-domain-0234-example.xx");
            Console.WriteLine(m.Groups[0].Value);
       }

这输出:

test.com

更乱的域0234-example.xx

请注意,此处对域​​名的正则表达式进行了很好的讨论:Domain name validation with RegEx

有些微妙的情况没有包含在您的正则表达式中。