Here is a sample expression that contains a bunch of f
and some other stuff:
expr = a f[x] + b f[y] + 2 c f[z] + f[a] + Cos[y] + 3 f[y] + Sqrt[x]
and I would like to apply function modify1
to the part of the expression containing f[x]
f[y]
and f[z]
exclusively (not f[a]
), and modify2
to the rest. The pattern that matches is: Plus[rest___, Times[_., f[x | y | z]] ..]
and I am using it like so:
expr /. Plus[rest___, Times[_., f[x | y | z]] ..] :> modify1[Plus[(*???*)]] + modify2[Plus[rest]]
modify1[] + modify2[Sqrt[x] + Cos[y] + f[a]]
What I want is:
modify1[a f[x] + b f[y] + 2 c f[z] + 3 f[y]] + modify2[Sqrt[x] + Cos[y] + f[a]]
To make this work, I need to name the part of the pattern that has all the f[x]
, f[y]
, f[z]
so I can apply the modify1
function to it. But if I try to insert a name to the pattern like so:
expr /. Plus[rest___, (name: Times[_., f[x | y | z]] ..)] :> modify1[Plus[name]] + modify2[Plus[rest]]
The pattern matches incorrectly:
modify1[a f[x]] + modify2[Sqrt[x] + Cos[y] + f[a] + 3 f[y] + b f[y] + 2 c f[z]]
How do I name Times[_., f[x | y | z]] ..
inside of Plus
so that the pattern correctly matches and can be subsequently manipulated? Note that the list of arguments x
y
z
is variable, so I prefer to avoid a brute force solution.