It is not entirely clear to me what you are actually trying to accomplish. Using subscripts in Mathematica often needlessly complicates things. Since you are looking for an automated replacement I think you prefer not to enter subscripts manually which I think is wise. I believe it also means you are looking for a formatting function.
A basic approach is to work with strings. We may write:
ux1 - i1 /. s_Symbol /; Context[s] === $Context :>
(Subscript[#, "" <> ##2] & @@ Characters @ SymbolName[s])
If string output is not acceptable we may wish to use HoldForm
to keep elements from evaluating. This is important if for example x1
or i
are Symbols with a value:
x1 = i = "Fail!";
ux1 - i1 /. s_Symbol /; Context[s] === $Context :>
(HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@ Characters @ SymbolName[s])
Additionally you may consider the case where these replacements must be done inside a held expression, where e.g. i1
has a global value. You will need Unevaluated
and RuleCondition
:
i1 = x1 = i = "Fail!";
Hold[ux1 - i1] /. s_Symbol /; Context[s] === $Context :>
RuleCondition[HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@
Characters @ SymbolName @ Unevaluated @ s]
If I am correct that you want this for formatting purposes you might make use of a formatting wrapper, which will allow you to extract the original unmodified expression, or define rules for function to work with that expression.
MakeBoxes[subscriptForm[expr_], fmt_] :=
MakeBoxes[#, fmt] &[
expr /. s_Symbol /; Context[s] === $Context :>
RuleCondition[HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@
Characters @ SymbolName @ Unevaluated @ s]
]
Now:
expr = subscriptForm[Hold[ux1 - i1]]
First @ expr
Hold[ux1 - i1]