4

Is there a way to use wildcards or a regex to search and remove items from HttpContext.Cache?

I can have in my cache "item_1", "item_2",...,"item_n" and I want to remove from cache all values that are related to keys with the pattern "item_*". How to achieve that without checking if the item exists and then remove it?

Ex:

instead of:

HttpContext.Current.Cache.Remove("item_1")
HttpContext.Current.Cache.Remove("item_2")
HttpContext.Current.Cache.Remove("item_3")

I want something like:

HttpContext.Current.Cache.Remove("item_*")
Buda Gavril
  • 21,409
  • 40
  • 127
  • 196

2 Answers2

3

You could loop the items like this:

foreach(var key in HttpContext.Current.Cache)
{
    if (key.StartsWith("item_"))
    {
        // remove the corresponding item here.
    }
}

The basic sample, and needs some tweaking to match your implementation.

AFAIK you can't remove items based on wildcards, as you need the specific key. (Please prove me wrong)

scheien
  • 2,457
  • 1
  • 19
  • 22
0
^HttpContext\.Current\.Cache\.Remove\("item_.*?"\)$

You can try this.Replace with empty string.See demo.

http://regex101.com/r/sU3fA2/65

vks
  • 67,027
  • 10
  • 91
  • 124