Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For example, the substitution (x + y) -> s fails here:

In[1]:= (-x - y) /. (x + y) -> s

Out[1]= -x - y

Of course, I could try applying the rule (-x - y) -> -s, but this strategy becomes unwieldy in more complicated cases. At the very least it would require duplicating a lot of rules. For example, if the expression to be transformed were something like

(x + y)^2 + 2 (-x - y)

...then I'd need to use something like

{(x + y) -> s, (-x - y) -> -s}

Is there a better way to transform the above expression to s^2 - 2 s?

share|improve this question
Not sure if you find it better: expr /. x -> (s - y) – Kuba Jan 16 '14 at 20:03
Use FullForm[x + y] and FullForm[-x - y] to see how those two expressions are different (or TreeForm if you are feeling daring). ReplaceAll is a dumb function that is not going to transform your expression for you. It may not be friendly, but it is reliable. In general, as Kuba has suggested, it's better to replace atomic elements. – wxffles Jan 16 '14 at 21:54
It sounds like the transformation you are trying to do it more mathematica than formal. In these cases you can consider Eliminate or GroebnerBasis too, e.g. like here It depends on the situation if they work well. – Szabolcs Jan 16 '14 at 23:24
up vote 3 down vote accepted

Here are two methods to create patterns that match; the first uses a default value, while the second uses an explicit Alternatives expression.

p1 = x (s_: - 1) + y (ss_: - 1);
p2 = (x | -x) + (y | -y);

expr = {x + y, x - y, -x + y, -y - x};

MatchQ[#, p1] & /@ expr
MatchQ[#, p2] & /@ expr
{True, True, True, True}

{True, True, True, True}

If you specify how you want to handle the sign in all cases I can recommend something for the replacement.

share|improve this answer
poly=(x + y)^2 + 2 (-x - y)//Simplify;
poly//.{(x + y)-> s}

(*(-2 + s) s*)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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