Pattern matching expressions that have been simplified

I run into this type of issue frequently when trying to apply known identities to complicated expressions: some of my expressions will have their forms simplified by mathematica in such a way that mathematica will not be capable of easily pattern-matching uniformly all the expressions. What are good ways of preventing premature reductions of complex expressions so that I can pattern match everything nicely?

Here's a simple example.

Say we have a table involving numbers $$a,b$$ generated as follows:

arr = Table[i*j a^i b^j, {i, 1, 5}, {j, 1, 5}]

$$\left( \begin{array}{ccccc} a b & 2 a b^2 & 3 a b^3 & 4 a b^4 & 5 a b^5 \\ 2 a^2 b & 4 a^2 b^2 & 6 a^2 b^3 & 8 a^2 b^4 & 10 a^2 b^5 \\ 3 a^3 b & 6 a^3 b^2 & 9 a^3 b^3 & 12 a^3 b^4 & 15 a^3 b^5 \\ 4 a^4 b & 8 a^4 b^2 & 12 a^4 b^3 & 16 a^4 b^4 & 20 a^4 b^5 \\ 5 a^5 b & 10 a^5 b^2 & 15 a^5 b^3 & 20 a^5 b^4 & 25 a^5 b^5 \\ \end{array} \right)$$

and furthermore let's say that we're working in regime for which $$a,b$$ are each so small that if the total power on both of them is larger than $$5$$ the term can be neglected. Then we might try to implement this via

arr /. a^i_ b^j_ :> RuleCondition[0, i + j > 5]

but the output is actually

$$\left( \begin{array}{ccccc} a b & 2 a b^2 & 3 a b^3 & 4 a b^4 & 5 a b^5 \\ 2 a^2 b & 4 a^2 b^2 & 6 a^2 b^3 & 0 & 0 \\ 3 a^3 b & 6 a^3 b^2 & 0 & 0 & 0 \\ 4 a^4 b & 0 & 0 & 0 & 0 \\ 5 a^5 b & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

because even though the terms in the corners are order $$6$$ they are not of the form given by the pattern since $$5ab^5$$ is represented as Times[5,Power[a,5],b]. Since there is no Power on the b it isn't matched by the pattern. Are there any ways to handle the corner cases without hardcoding new patterns especially for them?

You can use Optional in your pattern, which has the short form of .:

arr = Table[i*j a^i b^j, {i, 1, 5}, {j, 1, 5}];

arr /. a^i_. b^j_. :> RuleCondition[0, i + j > 5] //TeXForm

$$\left( \begin{array}{ccccc} a b & 2 a b^2 & 3 a b^3 & 4 a b^4 & 0 \\ 2 a^2 b & 4 a^2 b^2 & 6 a^2 b^3 & 0 & 0 \\ 3 a^3 b & 6 a^3 b^2 & 0 & 0 & 0 \\ 4 a^4 b & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

Another alternative is to use Series:

Series[arr /. s:(a|b) -> s t, {t, 0, 5}] //Normal //ReplaceAll[t->1] //TeXForm

$$\left( \begin{array}{ccccc} a b & 2 a b^2 & 3 a b^3 & 4 a b^4 & 0 \\ 2 a^2 b & 4 a^2 b^2 & 6 a^2 b^3 & 0 & 0 \\ 3 a^3 b & 6 a^3 b^2 & 0 & 0 & 0 \\ 4 a^4 b & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

• Wow, using . seems obvious now but I would not have thought of it! Nov 26 '19 at 20:46
• Why isn't RuleCondition documented? Its usage has been discussed on this site for years and there doesn't seem to be any reason not to have this documented Nov 26 '19 at 23:02
• @MikeHoneychurch special treat for stackexchange users I guess... Nov 27 '19 at 20:58