简体   繁体   中英

Regex isMatch for cache pattern key

I wrote test for my cache extension. I want to delete from cache by pattern.

a) In this example test fails

 [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) In this example test passes

 [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();
    }

Why Regex IsMatch doesn't match pattern "shouldFoundThis-{0}-{1}-{3}" but matches pattern "shouldFoundThis-{0}-{1}"

The regex shouldFoundThis-{0}-{1}-{2} is identical to the regex shouldFoundThis--- , and there are no three dashes in sequence to be found in your subject string.

In constrast, shouldFoundThis-{0}-{1} is the same as shouldFoundThis- which can be found in your string.

In a regex, x{n} means " n repetitions of x ". Read more about quantifiers here .

You probably meant something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM