# Simplifying algebraic expression using pattern

Given the following expression

expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];


I would like to achieve the following output:

output = x Cos[y]^2 + Sin[x^2 z Cos[y]^2]


I tried it with case

Cases[expr, t : _Cos :> t^2, All]


but the result is not what I expected.

• Do I understand correctly: You want to get all terms that contain Cos somewhere in them, and then replace each Cos[...] with Cos[...]^2? Sep 21, 2023 at 11:09
• @Domen That is precisely right. But I wanted to do that by matching patterns for the Head. Sep 21, 2023 at 12:02

May be you need two patterns?

ClearAll["Global*"]
expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];
pat = {h_.*f_[g_.*(t : _Cos)] :> h*f[g*t^2], g_.*(t : _Cos) :> g*t^2};
Plus @@ Flatten[Cases[expr, #] & /@ pat]


Alternatives does not work, since Cases matches on first Alternative found, not all of them.

Here is another way using replace, which I think is simpler

ClearAll["Global*"]
expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];
expr = DeleteCases[expr, x_ /; FreeQ[x, _Cos]];
expr /. Cos[t_] :> Cos[t^2]