Wolfram Computation Meets Knowledge

ContainsQ

Contributed by: Taliesin Beynon (Wolfram Research)

Determine whether an input expression contains one or more subexpressions (at any level) matching a given pattern.

ResourceFunction["ContainsQ"][expr, pattern]

returns True if expr contains a subexpression at any level mathing pattern, and returns False otherwise.

ResourceFunction["ContainsQ"][pattern]

is an operator for of ContainsQ that can be applied to an expression.

Details and Options

ContainsQ is the negation of FreeQ.

Examples

Basic Examples

Test a basic expression for the presence of a given pattern:

In[1]:=
ResourceFunction["ContainsQ"][x + y^z, Power[_, _]]
Out[1]=

Test for another pattern:

In[2]:=
ResourceFunction["ContainsQ"][x + y^z, Times[_, _]]
Out[2]=

Properties and Relations

ContainsQ includes heads in the subexpressions it tests against pattern:

In[3]:=
ResourceFunction["ContainsQ"][f[a, b], f]
Out[3]=

ContainsQ counts matches at levelspec 0 (the full expression):

In[4]:=
ResourceFunction["ContainsQ"][f[a, b], f[a, b]]
Out[4]=

Resource History