# Pattern Matching Terms with Plus or Minus

I was playing with pattern matching and I ran into something I didn't expect. I imagine the following line would return True, but it returns False:

MatchQ[x, (+1 | -1) a_]


This will return True:

MatchQ[-x, (+1 | -1) a_]


Digging slightly deeper with FullForm I find the reason for this; FullForm[-a] returns Times[-1, a] whereas FullForm[a], of course, returns a. What's the best way to return True for both cases? Does Mathematica have an equivalent to the ? symbol in regular expressions which matches a group zero or one times?

I've also tried

MatchQ[x, (Nothing | -1) a_]


which again returns False.

• This would work: MatchQ[x, fact_. a_Symbol /; Abs[fact] == 1] It matches only if the factor in front of a symbol is +1 or -1. Nothing is not meant to be used in pattern matching. Sep 6, 2016 at 18:57
• What would be an example of a match failure you would hope to see with the pattern you are searching for?
– Alan
Sep 6, 2016 at 20:12
• @Szabolcs Thank you, _. was just what I needed to know about. @Alan 2x would fail to match. Sep 6, 2016 at 23:32

FullForm (and Head) is useful in seeing what lies under the hood.

FullForm@x


x

Head@x


Symbol

and

FullForm@-x


Times[-1,x]

Head@-x


Times

Now

(+1 | -1) a_ // FullForm


Times[Alternatives[1,-1],Pattern[a,Blank[]]]

That's why -x matches the pattern and x does not. For a fix:

MatchQ[x, -1 a_ | _Symbol]


True

MatchQ[-x, -1 a_ | _Symbol]


True

MatchQ[2 x, -1 a_ | _Symbol]


False

MatchQ[-2 x, -1 a_ | _Symbol]


False