正则表达式是缓存模式键的匹配

时间:2014-11-14 14:18:35

标签: c# .net regex

我为缓存扩展编写了测试。我想通过模式从缓存中删除。

a)在此示例中,测试失败

 [Test]
    public void Should_found_by_pattern()
    {
        string pattern = "shouldFoundThis-{0}-{1}-{2}";
        var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
        var keysToRemove = new List<String>();

        var list = new List<string>()
        {
            "shouldFoundThis-15-2-7"
        };

        foreach (var item in list)
            if (regex.IsMatch(item))
                keysToRemove.Add(item);

        keysToRemove.Any().ShouldBeTrue();
    }

b)在此示例中,测试通过

 [Test]
    public void Should_found_by_pattern()
    {
        string pattern = "shouldFoundThis-{0}-{1}";
        var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
        var keysToRemove = new List<String>();

        var list = new List<string>()
        {
            "shouldFoundThis-15-2"
        };

        foreach (var item in list)
            if (regex.IsMatch(item))
                keysToRemove.Add(item);

        keysToRemove.Any().ShouldBeTrue();
    }

为什么Regex IsMatch不匹配模式&#34; shouldFoundThis- {0} - {1} - {3}&#34;但匹配模式&#34; shouldFoundThis- {0} - {1}&#34;

1 个答案:

答案 0 :(得分:4)

正则表达式shouldFoundThis-{0}-{1}-{2}与正则表达式shouldFoundThis---相同,并且在主题字符串中找不到三个破折号。

相反,shouldFoundThis-{0}-{1}shouldFoundThis-相同, 可以在您的字符串中找到。

在正则表达式中,x{n}表示&#34; n重复x&#34;。详细了解quantifiers here

你可能意味着像

string pattern = @"shouldFoundThis-\d+-\d+-\d+";