Replacement question

I have this equation

 F2 + F4 - V1 + V3==0


I want it to be converted automatically via a replacement rule to

   Subscript[F, 2][x, t] + Subscript[F, 4][x, t] -
Subscript[V, 1][x, t] + Subscript[V, 3][x, t]==0


I have so many terms that's why I need the conversion to be automatic.

Thanks for the help.

• This seems like a bad idea, unfortunately the accepted answer didn't warn you about that. My advice is to follow the advice from Bob Hanlon (+1) and use Subscript only for display. The accepted answer does answer the request, but it's bad advice. Commented Sep 29, 2022 at 16:34

It is generally much easier to work with indexed variables. You can Format the display of the variables in any desired manner.

(Format[#[n_]] := Subscript[#, n]) & /@ {F, V};

eqn = F[2] + F[4] - V[1] + V[3] == 0


eqn2 = eqn /. sym_[int_] :> sym[int][x, t]


Or in situations where other similar forms are present that should not have the dependencies added, use the more specific

eqn2 = eqn /. sym_?(MemberQ[{F, V}, #] &)[int_Integer] :>
sym[int][x, t]


• Instead of sym_?(MemberQ[{F, V}, #] &) you can use (F | V) Commented Sep 29, 2022 at 20:47

First, pactelize the resource function SymbolToSubscript using PacletizeResourceFunction as follows:

ResourceFunction["PacletizeResourceFunction"]["SymbolToSubscript"]


Using SymbolToSubscript with your equation:

SymbolToSubscript[F2 + F4 - V1 + V3 == 0]
(*Subscript[F, 2] + Subscript[F, 4] - Subscript[V, 1] + Subscript[V, 3] == 0*)


Or without pacletize the resource function SymbolToSubscript:

ResourceFunction["SymbolToSubscript"][F2 + F4 - V1 + V3 == 0]
(*Subscript[F, 2] + Subscript[F, 4] - Subscript[V, 1] + Subscript[V, 3] == 0*)


To give an answer, some more info is needed. I assume that the variable names consists of a character followed by a digit. Otherwise, the RegularExpression must be adapted. With this assumptions, we can define a function that does the replacements:

makeSub[ex_] := Module[{str = ToString[ex]},
str = StringReplace[str,
RegularExpression["(\\w)(\\d)"] :>  "\!$$\*SubscriptBox[\($$1$$, $$$$2$$]\)"];
ToExpression[str]
]


We may test with your example:

makeSub[F2 + F4 - V1 + V3 == 0 ]


To include the arguments we may define:

m

akeSub[ex_] :=
Module[{str = ToString[ex]},
str = StringReplace[str,
RegularExpression["(\\w)(\\d)"] :>
"\!$$\*SubscriptBox[\($$1$$, $$$$2$$]\)[x,t]"];
ToExpression[str]]
makeSub[F2 + F4 - V1 + V3 == 0]


expr = F21 + F4 - V1 + V3 == 0;

ToExpression @ StringJoin @
SequenceReplace[
Characters[ToString @ expr],
{a_?LetterQ, b__?DigitQ} :> ToString[Subscript[a, StringJoin[{b}]], StandardForm]]