Questions on expression testing and manipulation through pattern matching and constructing efficient patterns.
The pattern matching is at the core of Mathematica and it is tightly integrated with and applicable to nearly every part of the system. All top-level computations are done in essence by expression manipulation through pattern matching. This symbolic pattern language generalizes concepts like regular expressions to describe general patterns for arbitrary symbolic structures using pattern-objects, like the Blank
family (_
, __
, ___
), Repeated
(..
, ...
), Alternatives
(|
), Except
, Optional
(:
), etc.
Accordingly, patterns and pattern matching can be used in:
- replacing parts of expressions using replacement rules (
Rule
->
andRuleDelayed
:>
used with theReplace
family of functions); consider adding the tag replacement; - expression testing (
Condition
/;
,PatternTest
?
withMatchQ
,MemberQ
,FreeQ
, etc.); consider adding the tag expression-test; - selecting subexpressions matching a pattern (
Cases
,DeleteCases
,Position
,Count
, etc.); consider adding the tag list-manipulation; - branching control structures forking if a pattern is matched (
If
,Switch
,Which
, etc.); - function definition and assignments (in costructs like
f[x_Real:0., y_List]:=...
); consider adding the tag function-construction.
Do not use this tag for pattern matching in strings. For such questions please use the tag string-manipulation or regular-expressions.
Useful links
- Patterns guide (pattern objects and pattern matching)
- Inside the Mathematica Pattern Matcher by Oyvind Tafjord (a useful and extensive introduction to Mathematica pattern matching)
- Rules & Patterns guide
- Testing Expressions guide (about predicate functions like
MatchQ
,FreeQ
, etc.) - Putting Constraints on Patterns tutorial (on how to use
Conditional
/;
)
Example questions