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
.
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. $\endgroup$_.
was just what I needed to know about. @Alan2x
would fail to match. $\endgroup$