Match match = Regex.Match("555-5555555", "^(\\d{3}\\-?\\d{3}\\-?\\d{4})$", RegexOptions.None);
it["Should match"] = () => match.Success.should_be_true();
我相信以上应该匹配。我需要数字,但将连字符保留为可选。但是,上面返回 false 并且测试失败。
编辑
接受的答案是 Darin 是对的,我的测试范围有问题。这是我通过的更新代码:
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();
};
}