How to define patterns to filter lists of replacement rules?
rules = {a -> 1, b -> 2, c -> 3};
FilterRules[rules, b]
(* {b -> 2} )*
or
Cases[{a -> 1, b -> 2, c -> 3}, PatternSequence[b -> _]]
(* {b -> 2} )*
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.