Replace expression, but only "outside" of a function [duplicate]

I have a horrid expression, which is basically a sum of exponents with coefficients. Here's a taste:

What I want to do is to replace ks with another expression, but to do so only when ks appears outside an exponent. Alternatively, I want to preform this replacement, but keep the arguments of all exponents unchanged.

For example I want

SpecialReplace[(ks-foo*bar) Exp[ks^foo-bar],ks->Y]


to yield

(Y-foo*bar) Exp[ks^foo-bar]


How would I do that?

• Related: (33025) Jan 14, 2015 at 14:56

Use two rules in the replacement with a dummy rule to replace exponents with themselves.

Along the lines of.

(ks-foo*bar) Exp[ks^foo-bar] /. {x:Exp[___]->x, ks->Y}


So anything that is an exponent is 'caught' by the first rule and the kx replacement rule doesn't get a look in.

• Thanks. But lists of replacement rules are executed consecutively, so this will not work. Jan 14, 2015 at 8:56
• You're right it doesn't work, I have corrected it. Not because the rules execute in sequence but because my first rule was incorrect. Jan 14, 2015 at 9:07

Try the following. Let this:

expr = (ks - foo1*bar1) Exp[ks^foo1 - bar1] + (ks - foo2*bar2) Exp[
ks*foo2 - bar2];


This

pos = Position[expr, Exp[__]];


returns the position of exponents in it. Then this:

 expr2 = MapAt[ReplaceAll[#, ks -> kg] &, expr, pos] /. ks -> Y /.
kg -> ks

(*   E^(-bar1 + ks^foo1) (-bar1 foo1 + Y) +
E^(-bar2 + foo2 ks) (-bar2 foo2 + Y)       *)


makes the job.

Have fun!