Wolfram Research

Function Repository Resource:

ContainsQ

Source Notebook

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

Contributed by: Taliesin Beynon

ResourceFunction["ContainsQ"][expr, pattern]

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

ResourceFunction["ContainsQ"][pattern]

is an operator form 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]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information