尝试匹配简单的电话号码 C# 正则表达式


Match match = Regex.Match("555-5555555", "^(\d{3}\-?\d{3}\-?\d{4})$", RegexOptions.None);
it["Should match"] = () => match.Success.should_be_true();

以上应该符合我相信。我需要数字,但将连字符保留为可选。但是,上述返回 false 并且未通过测试。

编辑

接受的答案,因为达林是对的,我的测试范围有问题。这是我通过的更新代码:

Match match;
    void describe_example()
    {
        context["goodregex"] = () =>
        {
            before = () => match = Regex.Match("555-5555555", "^(\d{3}\-?\d{3}\-?\d{4})$", RegexOptions.None);
            it["Should match"] = () => match.Success.should_be_true();
        };
        context["badregex"] = () =>
        {
            before = () => match = Regex.Match("555-5525-5555", "^(\d{3}\-?\d{3}\-?\d{4})$", RegexOptions.None);
            it["Should not match"] = () => match.Success.should_be_false();
        };
    }

以下程序打印为 true:

class Program
{
    static void Main()
    {
        var match = Regex.Match("555-5555555", "^(\d{3}\-?\d{3}\-?\d{4})$", RegexOptions.None);
        Console.WriteLine(match.Success);
    }
}

我猜您在单元测试中遇到了一些范围问题,其中并发运行测试时正在修改match变量。

您的正则表达式在我的机器上正常工作。对于验证不同类型电话号码的正则表达式,请查看此处(您可以与您的需求进行比较并选择最合适的一个):

http://www.regexlib.com/Search.aspx?k=phone&AspxAutoDetectCookieSupport=1

正则表达式对我来说看起来不错。事实上,在我的机器上match.Success也是如此。我可能会将正则表达式重写为:

"^(\d{3}\-?){2}\d{4}$"

但是,这只是偏好问题。

最新更新