# How to force a replacement in an order that I want?

This is a follow-up to this question.

I have a big sum, with lots of terms of the form

Times[Complex[0, Rational[-1, 4]], Power[2, Rational[-1, 2]], Aurb, Bdrb, h]


Each term in the sum consists of five objects, 2 numbers, one h[i] and an object starting with A, e.g. Aurb and an object starting with B, as for example, Bdrb.

I want to transform every term such that I have only terms of the form

Times[ComplexNumber, RealNumber, h[i], KroneckerProduct[A..., B...]],


for the term above

Times[Complex[0, Rational[-1, 4]], Power[2, Rational[-1, 2]], h, KroneckerProduct[Aurb, Bdrb]]


The important thing is that always the A... and B... are put into the KroneckerProduct. How can I tell the Mathematica to always replace my terms like this? Ideally, I want that Mathematica checks for all elements that are part of a given list, for example MemberQ[All my objects starting with A, ...] and put it then at the correct spot in the replacement rule.

• Why do you have ellipses (...) after the A and B variables? Are there sometimes more than one of each of the variables showing up? By the way, the matching would be a lot easier if you decided to name the variables with Heads a and b instead: for instance, use a[urb] and b[drb] instead of aurb and bdrb. Then, this expression manipulation will be much easier to do. Jan 2, 2016 at 19:07
• @march Thanks for your comment. The ellipses denote rest of the name for this object. I did not number them as the h[i], but there is always only one of each object. Given a better naming, as for example a[urb], how could replacement rule be achieved?
– jak
Jan 2, 2016 at 19:11

fun = Times[Complex[0, Rational[-1, 4]], Power[2, Rational[-1, 2]], Aurb, Bdrb, h];

Times @@ Complement[List @@ fun, #] KroneckerProduct @@ # &[Cases[fun, _Symbol]] With

foo = Times[Complex[0, Rational[-1, 4]], Power[2, Rational[-1, 2]], Aurb, Bdrb, h]


Then

foo /. (a_Symbol b_Symbol) -> KroneckerProduct[a, b]


If you want to be more strict on the name of the symbols then

foo /. ((a_Symbol /; StringTake[SymbolName@a, 1] == "A")
(b_Symbol /; StringTake[SymbolName@b, 1] == "B")) -> KroneckerProduct[a, b]


Hope this helps