WolframLang: Pattern Syntax

By Xah Lee. Date: . Last updated: .

Here's a list of all pattern syntax. [see Pattern Matching]

Literal expression stand by itself. It can also be used in pattern matching. For example: symbol a matches itself, number 3 matches itself, string "abc" matches itself, and arbitrary expression f[a,b,c] matches itself.

_
any Expression

same as Blank[]

Blank

ReplaceAll[ {3,4}, _ -> x ] === x
x_
any expression, given the name x

same as Pattern[x, Blank[]]

Pattern

ReplaceAll[ {3,4}, x_ -> x+y ] === {3 + y, 4 + y}
_h
any expression with Head h
ReplaceAll[ {3, a, 4.5}, _Integer -> n ] === {n, a, 4.5}

ReplaceAll[ {3, a, 4.5}, _List -> n ] === n

ReplaceAll[ {3, f[a], 4.5}, _f -> n ] === {3, n, 4.5}
x_h
any expression with Head h, given the name x
ReplaceAll[ {3, a}, x_List -> f[x] ] === f[{3, a}]

ReplaceAll[ {3, f[a]}, x_f -> g[x] ] === {3, g[f[a]]}
__
any sequence of one or more expressions. (2 LOW LINE characters)

BlankSequence

___
any sequence of zero or more expressions (3 LOW LINE characters)

BlankNullSequence

x__ and x___
sequences of expressions, given the name x
__h and ___h
sequences of expressions, each with Head h
x__h and x___h
sequences of expressions with Head h, given the name x
x:pattern
a pattern, given the name x
pattern?test
a pattern that yields True when test is applied to its value

PatternTest

PatternSequence[p1, p2, etc]
a sequence of patterns
OrderlessPatternSequence[p1, p2, etc]
an orderless sequence of patterns
KeyValuePattern[{‹key1› → ‹val1›, etc}]
an orderless sequence of key → val pairs
x_:v
an expression with default value v

Optional

x_h:v
an expression with Head h and default value v
x_.
an expression with a globally defined default value
Optional[x_h]
an expression that must have Head h, and has a globally defined default value
Except[c]
any expression except one that matches c
Except[c, pattern]
any expression matching pattern, except one that matches c
pattern..
a pattern repeated one or more times

Repeated

pattern...
a pattern repeated zero or more times
Repeated[pattern, spec]
a pattern repeated according to spec
p1|p2|etc
a pattern that matches at least one of the pattern.

same as Alternatives[p1, p2, etc]

Alternatives
pattern/;cond
a pattern for which cond evaluates to True

Condition

HoldPattern[pattern]
a pattern not evaluated
Verbatim[expr]
an expression to be matched verbatim
OptionsPattern[]
a sequence of options
Longest[pattern]
the longest sequence consistent with pattern
Shortest[pattern]
the shortest sequence consistent with pattern

PatternsAndTransformationRules

Pattern Matching