Division and subtraction do not really exist outside of explicit uses of the literal heads Divide
and Subtract
, otherwise these operations are directly converted into addition and multiplication. Although this can make pattern matching easier in some cases it also makes it more confusing in others like yours. See Why are numeric division and subtraction not handled better in Mathematica? for another consequence of this.
Pattern matching takes place on (something close to) the FullForm
of an expression, not the "pretty-printed" display form that you see in the Notebook. You need to either write patterns mindful of this or find ways around it. One way around it is processing like Numerator
and Denominator
as halirutan shows. This is preferred when possible. Another is to leverage the low-level Box form behind the display form. For example the cleanest way to match radicals in output is to look for SqrtBox expressions, and some expressions may need to be converted to and from boxes to make seemingly apparent replacements possible.
You can see that in FullForm your two expressions contain x
differently:
y/x^2 // FullForm
y/(x^2 + 1) // FullForm
Times[Power[x, -2], y]
Times[Power[Plus[1, Power[x, 2]], -1], y]
Now in Box form as used by the Front End for display:
y/x^2 // ToBoxes
y/(x^2 + 1) // ToBoxes
FractionBox["y", SuperscriptBox["x", "2"]]
FractionBox["y", RowBox[{"1", "+", SuperscriptBox["x", "2"]}]]
One can work off of the SuperscriptBox
similarity. This (overly simple) utility function will convert both an expression and a the rule to Box form, do the ReplaceAll
, then convert it back again:
boxReplace[expr_, {rule__} | rule_] :=
ToBoxes[expr] /. Map[ToBoxes, {rule}, {2}] // ToExpression
Example:
boxReplace[{y/x^2, y/(x^2 + 1)}, x^2 -> k]
{y/k, y/(1 + k)}
y/x^2 // FullForm
$\endgroup$y/x^2
is regraded asy*Power[x,-2]
$\endgroup$