Different behaviours of Cases

As an alternative to HoldPattern[Evaluate[...] you can use PatternSequence which evaluates its argument:

{Cases[{1, a -> 2 b}, PatternSequence[a -> 2 b]],
 Cases[{1, a -> 1/2 b}, PatternSequence[a -> 1/2 b]],
 Cases[{1, a -> π b}, PatternSequence[a -> π b]],
 Cases[{1, a -> c b}, PatternSequence[a -> c b]]}

{{a -> 2 b}, {a -> b/2}, {a -> b π}, {a -> b c}}

Alternatively, give the pattern a name:

{Cases[{1, a -> 2 b}, p : (a -> 2 b)],
 Cases[{1, a -> 1/2 b}, p : (a -> 1/2 b)],
 Cases[{1, a -> π b}, p : (a -> π b)],
 Cases[{1, a -> c b}, p : (a -> c b)]}

{{a -> 2 b}, {a -> b/2}, {a -> b π}, {a -> b c}}


Thanks to Kuba's comment now I see: HoldPattern prevents the evaluation of its argument, so Cases don't match the element in the list a->b/2 that is

Times[Rational[1, 2], b]

with the unevaluated pattern

Times[b, Power[2, -1]]

Evaluate the argument of HoldPattern solves the problem:

Cases[{1, a -> b/2}, HoldPattern[Evaluate[a -> b/2]]]
(*{a -> b/2}*)

Thanks Kuba!


Here is another way by using Verbatim. Maybe it feels a bit less hacky.

{
 Cases[{1, a -> 2 b}, Verbatim[a -> 2 b]],
 Cases[{1, a -> 1/2 b}, Verbatim[a -> 1/2 b]],
 Cases[{1, a -> π b}, Verbatim[a -> π b]],
 Cases[{1, a -> c b}, Verbatim[a -> c b]]
 }

{{a -> 2 b}, {a -> b/2}, {a -> b π}, {a -> b c}}