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

时间:2015-01-09 11:12:43

标签: c# regex mono

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

        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检查器检查并得到了#34;您的模式匹配但是没有(捕获(组))匹配主题字符串中的任何内容。"

为什么我不会在无效字符上出错?

谢谢。

1 个答案:

答案 0 :(得分:1)

你的正则表达式基本上是正确的(但请看下面的链接),这个测试方法证实了它:

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

更杂乱-domain0234-example.xx

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

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