# selective replacement rules in mathematical expression

I am trying to write a replacement rule that will substitute values for d_1 and d_2 only the places they are outside the Phi equation:

I was able to write a function that replaced Phi[d_1] and Phi[d_2] with Phi[d1] and Phi[d2], thereby creating two new variables and then apply my transformation rules only to the original d_1 and d_2. But this does not generalize for when the function Phi contains a linear combination of d_1 and d_2, or some other value that I don't want to substitute for. Can you help me figure how to do this?

In mathematica code:

E^(-2 r T) k^2 (1 + E^(
2 Subscript[d, 1] (Subscript[d, 1] - Subscript[d, 2])) +
2 E^(1/2 (\!$$\*SubsuperscriptBox[\(d$$, $$1$$, $$2$$] -
\*SubsuperscriptBox[$$d$$, $$2$$, $$2$$]\))) (-1 + \[CapitalPhi][
Subscript[d, 1]]) -
1] (Subscript[d, 1] - Subscript[d, 2])) \[CapitalPhi][
2 Subscript[d, 1] - Subscript[d, 2]] - \[CapitalPhi][Subscript[d,
2]])


Or, for easier copy/paste (brackets corrected):

E^(-2 r T) k^2 (1 + E^(2 Subscript[d, 1] (Subscript[d, 1] - Subscript[d, 2])) + 2 E^(1/2 (\!$$\*SubsuperscriptBox[\(d$$, $$1$$, $$2$$] -\*SubsuperscriptBox[$$d$$, $$2$$, $$2$$]\))) (-1 + \[CapitalPhi][Subscript[d, 1]]) - E^(2 Subscript[d, 1] (Subscript[d, 1] - Subscript[d, 2])) \[CapitalPhi][2 Subscript[d, 1] - Subscript[d, 2]] - \[CapitalPhi][Subscript[d,2]])

• Please enter your expression in a code block using Mathematica code. – Bob Hanlon Sep 7 '16 at 2:55
• edited accordingly – pyrex Sep 7 '16 at 3:16
• There brackets don't balance so the expression will not evaluate – Bob Hanlon Sep 7 '16 at 3:24
• Something on the lines of yourexpression /. {a : Φ[___] :> a, Subscript[d, a : 1 | 2] :> ToExpression["d" <> IntegerString[a]]}? The first replacement prevents other replacements of expressions with head Φ. – JungHwan Min Sep 7 '16 at 3:32
• corrected the brackets on the copy/paste version – pyrex Sep 7 '16 at 3:36

You could exploit the fact that ReplaceAll does not replace the same thing twice.

For instance:

In[505]:= eq /. {a_Φ :> a,
Subscript[d, a : 1 | 2] :>
ToExpression["d" <> IntegerString[a]]}

Out[505]//InputForm=
(k^2*(1 + E^(2*d1*(d1 - d2)) + 2*E^((d1^2 - d2^2)/2)*
(-1 + Φ[Subscript[d, 1]]) - E^(2*d1*(d1 - d2))*
Φ[2*Subscript[d, 1] - Subscript[d, 2]] - Φ[Subscript[d, 2]]))/
E^(2*r*T)


(eq is the equation in your question)

The first replacement a_Φ :> a doesn't do anything, but it tells ReplaceAll not to replace sub-expressions of Φ anymore.

P.S. Thanks @march for the comment (a : Φ[___] changed to a_Φ).

• In this case, you could also do a_Φ :> a. – march Sep 7 '16 at 3:46
• Thank you so much everyone for the prompt reply, this was exactly what i was looking for. – pyrex Sep 7 '16 at 5:23