# Pattern matching problems involving FullForm and Plus and Times

I am trying to match an expression that will be a sum of more than one terms, with the last one being a product. For example, the objecta+b+x*y. I am using the FullForm of the expression, which is the form Plus[a,b,Times[x,y]]. After reviewing documentation, pattern Plus[__,Times[_]] seems to be what I am looking for, and it gives correct result:

However, when I apply FullForm to the expression before trying the match, the pattern fails.

¿Why does this happen? I thought that the FullForm evaluation was performed beforehand.

• Take a look at FullForm[Plus[a, b, Times[x, y]]] // FullForm. So you have to modify the pattern. e.g. MatchQ[FullForm[Plus[a, b, Times[x, y]]], _[Plus[__, Times[_]]]] Jul 18 at 18:14
• Your have more problems beyond the misuse of FullForm. See my answer below for details Jul 18 at 20:11

Beside following the good advice Rohit Namjoshi has given in a comment, you need to become aware that pattern matching against Plusand Times is tricky because these operators have attributes (special rules) that cause strange things to happen when the patterns containing them are evaluated.

Consider the following:

You don't want

MatchQ[Plus[a, b, foo[x, y]], Plus[__, Times[_]]]


to return True but it does. The reason for this is that

Plus[__, Times[_]] // FullForm


gives

    Plus[Blank[], BlankSequence[]]


which will match any Plus expression with two or moore arguaments. What you want is something like

MatchQ[Plus[a, b, Times[x, y]], Plus[__, Times[__]]]


but that doesn't work either because

Plus[__, Times[__]] // FullForm


gives

    Times[2, BlankSequence[]]


So what to do? I recommend using Inactivate.

Inactivate[MatchQ[a + b + x*y, Plus[__, Times[__]]], Plus | Times]
(* True *)

Inactivate[MatchQ[a + a + x*x, Plus[__, Times[__]]], Plus | Times]
(* True *)

Inactivate[MatchQ[a + b + foo[x, y], Plus[__, Times[__]]], Plus | Times]
(* False *)


### Update

On second thought perhaps using HoldPattern is better.

MatchQ[a + b + x*y, HoldPattern[Plus[__, Times[__]]]]
(* True *)

MatchQ[a + a + x*x, HoldPattern[Plus[__, Times[__]]]]
(* True *)

MatchQ[a + b + foo[x, y], HoldPattern[Plus[__, Times[__]]]]
(* False *)