This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
Wolfram Research, Inc.

IntroductionNaming Pieces of Patterns

2.3.2 Finding Expressions That Match a Pattern

Picking out elements that match a pattern.

This gives the elements of the list which match the pattern x^_.

In[1]:= Cases[ {3, 4, x, x^2, x^3}, x^_ ]

Out[1]=

Here is the total number of elements which match the pattern.

In[2]:= Count[ {3, 4, x, x^2, x^3}, x^_ ]

Out[2]=

You can apply functions like Cases not only to lists, but to expressions of any kind. In addition, you can specify the level of parts at which you want to look.

Searching for parts of expressions that match a pattern.

This returns a list of the exponents n.

In[3]:= Cases[ {3, 4, x, x^2, x^3}, x^n_ -> n]

Out[3]=

The pattern _Integer matches any integer. This gives a list of integers appearing at any level.

In[4]:= Cases[ {3, 4, x, x^2, x^3}, _Integer, Infinity]

Out[4]=

Limiting the number of parts to search for.

This gives the positions of the first two powers of x appearing at any level.

In[5]:= Position[ {4, 4 + x^a, x^b, 6 + x^5}, x^_, Infinity, 2]

Out[5]=

The positions are specified in exactly the form used by functions such as Extract and ReplacePart discussed in Section 1.8.

In[6]:= ReplacePart[ {4, 4 + x^a, x^b, 6 + x^5}, zzz, % ]

Out[6]=

Deleting parts of expressions that match a pattern.

This deletes the elements which match x^n_.

In[7]:= DeleteCases[ {3, 4, x, x^2, x^3}, x^n_ ]

Out[7]=

This deletes all integers appearing at any level.

In[8]:= DeleteCases[ {3, 4, x, 2+x, 3+x}, _Integer, Infinity ]

Out[8]=

Finding arrangements of an expression that match a pattern.

This finds all ways that the sum can be written in two parts.

In[9]:= ReplaceList[a + b + c, x_ + y_ -> g[x, y]]

Out[9]=

This finds all pairs of identical elements. The pattern ___ stands for any sequence of elements.

In[10]:= ReplaceList[{a, b, b, b, c, c, a},

{___, x_, x_, ___} -> x]

Out[10]=

IntroductionNaming Pieces of Patterns