# Applying rules to rewrite expressions that contain patterns

I'm trying to write a rule that can rewrite a pattern that exists in another expression. For some reason, this is proving to be more challenging than I expected ... most likely because I'm not totally understanding how Mathematica implements its pattern matching mechanism.

Here's my simple test case:

foo = Foo[a: {A,B,C}, b: {a,b,c}]    (* FullForm yields: Foo[Pattern[a,A],Pattern[b,B]] *)


I want to rewrite the portion b : {a,b,c} with some other expression, like Reverse[<b>] which should yield: b : {c,b,a}.

Here's what I've tried to far (none of which works):

foo /. (b:X_) -> Reverse[X]                 (* #1 produces Foo[b: {a,b,c}, a: {A,B,C}] *)

foo /. Hold[(b : B_)] -> Reverse[B]         (* #2 no effect *)

foo /. HoldForm[(b : B_)] -> Reverse[B]     (* #3 no effect *)

foo /. HoldPattern[(b : B_)] -> Reverse[B]  (* #4 same as case #1 *)

foo /. (b : B_List) -> Reverse[B]           (* #5 reverses both a:{} and b:{} *)

• You may also be interested in expression parsers. Two examples which come to mind are here and here (function depends). – Leonid Shifrin Mar 13 '14 at 11:01

foo /. HoldPattern[Pattern][Verbatim[b], x_] :> Pattern[b, Reverse@x]