Wolfram Language Fast Introduction for Programmers
Get Started »

Patterns

The Wolfram Language's pattern language lets you describe patterns for arbitrary symbolic structures, allowing powerful regex-like manipulation to be generalized to any expression and any form of data.

The Wolfram Language's pattern notation is a way of operating on generic tree structures in a similar way to how regular expressions operate on strings in both Python and the Wolfram Language. Patterns are more general and powerful for both small- and large-scale programming.

Patterns stand for classes of expressions.
The basic pattern construct _ (pronounced blank) stands for any expression.

Find cases in a list matching the pattern f[_]:

In[1]:=
X
Out[1]=

x_ (short for x:_) stands for a pattern whose value will be named x:

The rule can be typed as ->

In[2]:=
X
Out[2]=

/. means replace everywhere:

In[3]:=
X
Out[3]=

The sort of structural metaprogramming shown here is unique to the Wolfram Language's symbolic structure.

This sort of structural metaprogramming is unique to the Wolfram Language's symbolic structure.

__ (double blank) stands for any sequence of expressions:

In[1]:=
X
Out[1]=

a | b | c stands for a, b, or c:

In[1]:=
X
Out[1]=

This usage of | resembles Java's regex notation, although in Java | can also indicate a bitwise OR.

This differs from Python, where | represents the bitwise OR operation in this context.

It works in heads, too:

In[2]:=
X
Out[2]=

_h stands for any expression with head h:

In[1]:=
X
Out[1]=

:> is a delayed rulethe analog of := for a rule.

QUICK REFERENCE: Operations Involving Patterns »

Check Your Understanding

Which of these patterns matches the expression g[1, 2, 3]?

g[_, _]

Incorrect. This pattern requires exactly two arguments.

_g

Correct.

g[1 | 2 | 3]

Incorrect. The target expression has three arguments, while this pattern only allows one argument.

Which of these picks out all elements from the list {f[1], g[2], f[5], g[3]} matching g[_]?

Cases[{f[1], g[2], f[5], g[3]}, _]

Incorrect. The pattern _ stands for any expression.

Cases[{f[1], g[2], f[5], g[3]}, g[_]]

Correct.

Cases[{f[1], g[2], f[5], g[3]}, _f]

Incorrect. This pattern matches only the expressions with the head f.

The result of the expression {f[1], f[5], f[x]} /. f[x_] x + 4 is:

{f[5], f[9], f[x + 4]}

Incorrect. The entire function, not just the argument, would be replaced by the argument plus 4.

{5, 9, x + 4}

Correct.

{f[1], f[5], x + 4}

Incorrect. The x_ matches any expression, not just ones that are literally the same as x.

{5, 9, f[x]}

Incorrect. The x_ matches any expression, including any that are literally the same as x.