I assume that you don't know the specific variables ahead of time (or else you could just type {u1, u2, u3}
. So, I'm further assuming that you want to pull out raw symbols. You can use Cases for this:
Cases[ex, _Symbol, Infinity]
(* {u1, u2, u3, u1, u2, u3} *)
Probably want to wrap that in Union, which will delete duplicates and also sort:
Union[Cases[ex, _Symbol, Infinity]]
(* {u1, u2, u3} *)
And to get strings, you can use ToString:
ToString /@ Union[Cases[ex, _Symbol, Infinity]]
(* to clarify that these are strings, full form is List["u1", "u2", "u3"] *)
You could also use SymbolName since we know these are symbols.
At this point, I'm not sure whether you're still wanting strings or if you're wanting u to be a raw symbol with subscripts. I guess we'll do both. First, the following assumes that your symbols are all of the form: one letter followed by some (non-zero) number of digits. If that assumption doesn't hold, we'll need to do something else.
Let's save our symbols in a variable:
symbols = Union[Cases[ex, _Symbol, Infinity]]
Now, this gets you the string version:
Subscript @@@ StringTakeDrop[SymbolName /@ symbols, 1]
Explanation, StringTakeDrop is analogous to TakeDrop. The number you specify is used both to Take and Drop, with the first element of the result being for Take and the second being for Drop. So, effectively splitting a list (or, in this case, a string) at some index. StringTakeDrop expects strings, obviously, so we map SymbolName over our list first. The resulting pairs are each in the form that Subscript can be applied directly to, so we MapApply it.
If you don't want strings, but symbols and integers, then we need to insert a step:
Subscript @@@ Map[ToExpression, StringTakeDrop[SymbolName /@ symbols, {1}], {-1}]
We're mapping at the -1 level (so basically the lowest level atoms), and ToExpression does what it sounds like.
Note that:
Subscript@@Map[ToExpression, StringTakeDrop[SymbolName[u12], {1}], {-1}]
gives Subscript[u, 12]
. If you wanted Subscript[u, 1, 2]
, then we'd need to adjust this slightly.