# How to define patterns to filter lists of replacement rules?

I have a list of replacement rules like

list˘of˘replacement˘rules = {a -> 1, b -> 2, c -> 3}


and I want to filter all the elements where ‘b’ is replaced by using Cases[] and a search pattern.
The following code does not work:

Cases[list˘of˘replacement˘rules, b -> _]


The result is {}.
How should the pattern be defined in order to get the result {b->2}?

• Cases[{a -> 1, b -> 2, c -> 3}, HoldPattern[Rule[b, _]]] – Artes Nov 17 '14 at 14:14
• This question was “put on hold” because it appears to be a simple mistake. But I don’t think so. I truly searched the documentation for a solution before posting this question. You just have to know about the existence of certain keywords like HoldPattern[] or PatternSequence[]. Otherwise you would not find them in the documentation. – Gerhard Wonner Nov 19 '14 at 13:19
• Very closely related but not about patterns: (69299) – Mr.Wizard Feb 9 '16 at 10:32

rules = {a -> 1, b -> 2, c -> 3};

FilterRules[rules, b]
(* {b -> 2} )*


or

Cases[{a -> 1, b -> 2, c -> 3}, PatternSequence[b -> _]]
(* {b -> 2} )*

• FilterRules is particularly practical since you may also use it with a rule b->something, even blank as second argument or with a list of such rules. In this case, it does not care for the rhs of those rules. – Adalbert Hanßen Apr 11 '16 at 18:11

Cases handles an expression with head Rule specially, providing replacement functionality, therefore you need to keep the literal head of your pattern from being Rule. Examples:

Cases[rules, _[b, _]]
Cases[rules, x : (b -> _)]
Cases[rules, HoldPattern[b -> _]]
Cases[rules, Verbatim[Rule][b, _]]


All evaluate to {b -> 2}. None of the patterns have the head Rule:

Head /@ {_[b, _], x : (b -> _), HoldPattern[b -> _], Verbatim[Rule][b, _]}

{_, Pattern, HoldPattern, Verbatim[Rule]}


Of course for this particular operation FilterRules is more direct.

• Isn't this a better place? And isn't this topic a duplicate? 69299. Moreover, what's up with @kglr 's memory? :) – Kuba Feb 9 '16 at 10:25
• @Kuba It would be nice if people would close things as duplicates when they are duplicates, rather than "easily found in the documentation." I am starting to think that even having that close reason is a mistake, as the same simple questions are asked repeatedly anyway. In this case I saw a closed question, noted the OP's comment, and agreed. – Mr.Wizard Feb 9 '16 at 10:28
• @Kuba No, wait x 2. (lol) That one is about Select and this is about Cases, and while kglr answered both with an alternative the direct answer is different. I am going to leave this open after all. – Mr.Wizard Feb 9 '16 at 10:30
• I don't mind the order, I'm ususaly trying to link to the best topic so it will be linked in more places. – Kuba Feb 9 '16 at 10:31
• Good point (2nd lol). – Kuba Feb 9 '16 at 10:33