# Replace rule also matching complex numbers

I'm having the replace rule:

rule = {-g_ x_^4 - 2 g_ x_^2 y_^2 - g_ y_^4 -> -g (x^2 + y^2)^2};

Now,

(2 Re[Hy Conjugate[Hx]] kx^4 vx vy)/(k^2 (kx^2 + ky^2)) + (
4 Re[Hy Conjugate[Hx]] kx^2 ky^2 vx vy)/(k^2 (kx^2 + ky^2)) + (
2 Re[Hy Conjugate[Hx]] ky^4 vx vy)/(k^2 (kx^2 + ky^2)) //. rule

Just spits the same expression back out. The expected output would be

(2 Re[Hy Conjugate[Hx]] (kx^2 + ky^2) vx vy)/k^2

Sure, I could remove the minus signs in the rule, but is it possible to match both + and -? Furthermore this also fails of one of the coefficients is a complex number, how can I tell Mathematica that this should also work with complex numbers?

If there is another way to do this, e.g., using Solve, I'd like to hear that.

• Can you also post your expected output? It's not clear what you want the final result to be
– rm -rf
Commented Feb 2, 2012 at 21:31
• What's the actual problem you're trying to solve? This looks like you're trying to re-code some simplifying algorithm that may already be implemented in Mathematica. Commented Feb 2, 2012 at 21:35
• @David: I have done so. The real expression is much longer, so Simplify does things that I don't want it to do! I have 'fixed' everything with the replace rules, but this term doesn't want to change :-). Commented Feb 2, 2012 at 21:37
• When I replace //. rule by // Simplify I get pretty much your desired output; I assume the discrepancies are typos. Commented Feb 2, 2012 at 21:40
• Could just use Factor on your expression, in this case at least. Commented Feb 2, 2012 at 22:09

## 1 Answer

Assuming you want to do all this with replacement rules rather than some built-in functions as noted in the comments, if you modify the rule and correct the typos you get the desired output from the example. For example:

rule2 = g_  x_^4 + h_   x_^2  y_^2 + g_  y_^4 /; h == 2 g ->
g (x^2 + y^2)^2 ;

and

(2 Re[Hy Conjugate[Hx]] kx^4 vx vy)/(k^2 (kx^2 + ky^2)) + (4 Re[
Hy Conjugate[Hx]] (kx^2  ky^2) vx vy)/(k^2 (kx^2 +
ky^2)) + (2 Re[
Hy Conjugate[Hx]] ky^4 vx vy)/(k^2 (kx^2 + ky^2)) //. rule2

gives

(2 (kx^2 + ky^2) vx vy Re[Hy Conjugate[Hx]])/k^2