MatchQ


In order for a pattern to match an expression, the pattern and the expression
it is compared with must have the same FullForm after evaluation.  For
example the expression a/b has the FullForm Times[a,Power[b,-1]], so it
doesn't match the pattern (_Rational).  MatchQ is a very good tool to use
when testing a pattern to see if it matches the intended expressions.  Some
interesting examples of MatchQ are given below.

{MatchQ[3/2, p_/q_], MatchQ[3/2, _Rational]}

{False, True}

The head HoldPattern used in next cell is explained in another section.

Clear[a, b] ;    {MatchQ[a/b, _Rational],   MatchQ[a/b, _/_],   MatchQ[a/b, HoldPattern[_/_]],   MatchQ[a/b, p_/q_]}

{False, False, True, True}

{MatchQ[a/2, p_/q_],       MatchQ[a/2, _Rational],       MatchQ[a/2, _ * _Rational]}

{False, False, True}

{MatchQ[1/Sqrt[b], _/Sqrt[_]], MatchQ[1/Sqrt[b], HoldPattern[_/Sqrt[_]]],       MatchQ[1/Sqrt[b], 1/Sqrt[_]]}

{False, False, True}

{MatchQ[a/Sqrt[b], _/Sqrt[_]],   MatchQ[a/Sqrt[b], HoldPattern[_/Sqrt[_]]],   MatchQ[a ... tern[x_/Sqrt[y_]]],   MatchQ[a/Sqrt[b], x_ * y_^(-1/2)], <br />MatchQ[a/Sqrt[b], x_/Sqrt[y_]]}

{False, False, False, False, True, True}

{MatchQ[2 + 3I, a_ + b_ * I], MatchQ[2 + 3I, _Complex]}

{False, True}

{MatchQ[a + b I, _Complex],   MatchQ[a + b I, _ + _Complex],   MatchQ[a + b I, _ + _ * ... _ * Complex[0, 1]]],   MatchQ[a + b I, _ + _ * _Complex ],   MatchQ[a + b I, x_ + y_ * I]}

{False, False, False, False, False, True, True, True}

data = {{2, 3}, {1, 4}, {6, 7}, {8, 6}, {2, 1}} ;    MatchQ[data, {{_, _} ..}]

True

I don't provide further examples, but any combination of pattern matching  constructs can be used with MatchQ.  Nuances of pattern matching are discussed in another section.


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page