Skip to content

MatchQ

MatchQ[expr, form] returns True if expr matches form, False otherwise.

Attributes[MatchQ] := {Protected}

Simple examples

A Blank[] expression matches everything:

In[1]:= MatchQ[2*x, _]
Out[1]= True
Although a more specific pattern would have matched as well:
In[2]:= MatchQ[2*x, c1_Integer*a_Symbol]
Out[2]= True
Since Times is Orderless, this would work as well:
In[3]:= MatchQ[x*2, c1_Integer*a_Symbol]
Out[3]= True
As would the FullForm:
In[4]:= MatchQ[x*2, c1_Integer*a_Symbol]
Out[4]= True
Named patterns must match the same expression, or the match will fail:
In[5]:= MatchQ[a + b, x_Symbol + x_Symbol]
Out[5]= False

Further examples

In[1]:= MatchQ[{2^a, a}, {2^x_Symbol, x_Symbol}]
Out[1]= True
In[2]:= MatchQ[{2^a, b}, {2^x_Symbol, x_Symbol}]
Out[2]= False
Blank sequences allow for the matching of multiple objects. BlankSequence (__) matches one or more parts of the expression:
In[3]:= MatchQ[{a, b}, {a, __}]
Out[3]= True
In[4]:= MatchQ[{a}, {a, __}]
Out[4]= False
BlankNullSequence (___) allows for zero or more matches:
In[5]:= MatchQ[{a}, {a, ___}]
Out[5]= True