Transformation rules to distinguish common variable with Subscript and OverBar $x,x^2,\bar{x},\bar{x}^2, x_p,x_p^2, \bar{x}_p, \bar{x}^2_p $
The real reason why this is not working is that Mathematica actually matches each x
inside Subscript
and OverBar
individually.
In other words, OverBar[x]
doesn't match your rule, but the internal x
individually matches the rule when ReplaceAll
goes to a deeper level in the expression.
To solve this problem, you can use the LevelSpec
option of the Replace
function to avoid matching on deeper levels.
Using the same definition for your rule1ALT
, you can do:
Replace[Times[x, Subscript[x, p], Subscript[y, p],
Subscript[OverBar[x], p]], rule1ALT, 1]
Which yields the correct desired output: $(\bar{x} + \tilde{x}) x_p y_p \bar{x}_p$.
However, this is not a universal solution! It will not work if you have the OverBar
and Subscript
symbols appearing in many different levels of the expression, which most probably you will. After all, there is no way to distinguish x
inside x^2
from x
inside OverBar[x]
if you traverse an expression hierarchically on all levels.
The best workaround in my opinion is to actually change the name of the variables, so that ReplaceAll
can work on them seamlessly on all levels, and only substitute the names at the end of calculation. For example, set y
to be OverBar[x]
and z
to be x_p
, go through your manipulations, then at the end of each calculation before displaying the results, do /. {y -> OverBar[x], z->x_p}