I'm learning to use the ReplaceAll function and I found the behavior of which is quite confusing.


Sqrt[f[x, y]] /. f[___] -> u

Mathematica returns


However, if I replace f with Plus, i.e.

Sqrt[Plus[x, y]] /. Plus[___] -> u

instead of returning Sqrt[u], Mathematica gives



a*Sqrt[x] /. Sqrt[_] -> u

Mathematica gives

a u

However, if the input is

a/Sqrt[x] /. Sqrt[_] -> u

Instead of returing a/u, Mathematica returns


I'm really confused. Can anybody shed some light on the behavior of this function?


Case #1


"anything" /. Plus[___] -> "match"

This is because Plus[___] evaluates to ___, and ___ matches anything. You can use HoldPattern:

Sqrt[Plus[x, y]] /. HoldPattern[Plus[___]] -> u

For this particular case you could also use the form _Plus, which matches any expression with head Plus but not Plus itself:

Sqrt[Plus[x, y]] /. _Plus -> u

Case #2

You must understand that pattern matching is done on something close to the FullForm of an expression, rather than the StandardForm output you normally see. Let's look at your second problematic expression:

a/Sqrt[x] // FullForm

As you can see, Sqrt is nowhere to be found.

You could prevent the evaluation of Sqrt on both the left-hand and right-hand sides:

Unevaluated[a/Sqrt[x]] /. HoldPattern[Sqrt[_]] -> u

If you need to match for things that appear as Radicals in StandardForm you can use the methods described here. An application of that might look like this:

ToBoxes[a/Sqrt[x]] /. _SqrtBox -> u // ToExpression
  • $\begingroup$ Great answer. As an mma beginner myself, I learnt quite a bit from it. It also made me realise that using Trace[] can be helpful in seeing how mma evaluates rules and matches patterns. I suggest OP might give it a whirl too. $\endgroup$
    – Aky
    Apr 9 '13 at 1:09
  • $\begingroup$ Thanks for the excellent answer. I find the 2nd solution on Case#2 very useful. $\endgroup$ Apr 9 '13 at 2:59
  • $\begingroup$ @Aky Thanks. Indeed Trace is helpful, and I just recommended it in an answer a few hours before this one, which is probably the only reason I did not mention it here. $\endgroup$
    – Mr.Wizard
    Apr 9 '13 at 11:17
  • $\begingroup$ @sy0116 I'm glad the answer is helpful to you. Be aware that the ToBoxes method should only be used when necessary; if it is possible to accomplish your transformations using mathematical tools you should do so. Operating on the box forms is a "last resort" as it were to manipulate what Mathematica shows you in StandardForm. What Mathematica displays as a radical is somewhat arbitrary (or at least not readily apparent) and this is the only way to know to match exactly those cases. $\endgroup$
    – Mr.Wizard
    Apr 9 '13 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.