Regex isMatch for cache key
I wrote a test for expanding the cache. I want to delete from cache by pattern.
a) In this example, the 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, the 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 does Regex IsMatch not match "shouldFoundThis- {0} - {1} - {3}" but match "shouldFoundThis- {0} - {1}"
source to share
Regular expression is shouldFoundThis-{0}-{1}-{2}
identical to regular expression shouldFoundThis---
, and there must be no three dashes in the subject line.
In constrast, is the shouldFoundThis-{0}-{1}
same as shouldFoundThis-
that found in your string.
In regular expression x{n}
means " n
repetitions x
". More on here>.
You probably meant something like
string pattern = @"shouldFoundThis-\d+-\d+-\d+";
source to share