# Questions tagged [pattern-matching]

Questions on expression testing and manipulation through pattern matching and constructing efficient patterns.

297 questions
5k views

### Using a PatternTest versus a Condition for pattern matching

My last question to the site resulted in several answers that involve using pattern matching in Mathematica, a feature I wasn't very familiar with at the time. I am currently reading Mathematica ...
4k views

### Find subsequences of consecutive integers inside a list

I have a list which is something like this: {3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46} What I'd like to to is get the intervals which are in ...
5k views

### Looking for “Longest Common Substring” solution

I'm looking for robust code to solve the "Longest Common Substring" problem: Find the longest string (or strings) that is a substring (or are substrings) of two or more strings. I can just code it ...
487 views

### Unexpected behavior of rule matching a pattern

I am a beginner exploring the world of Mathematica. I expected the following code T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] -> Length[List[b]]} should return ...
646 views

### Why doesn't PatternTest work with Composition?

While playing around with the solutions to this question, I've found some very strange behaviour: ...
3k views

### How do I perform string matching and replacements?

What are, and how do I use Mathematica's string matching and replacement tools?
3k views

### What best practices or performance considerations are there for choosing between Cases, Position, Pick and Select?

Cases, Select,Pick and Position each have different ...
2k views

### How to Combine Pattern Constraints and Default Values for Function Arguments?

EDIT: As several respondents have noted in the answers and comments below, the original example had a default value that would never be used because of the way patterns and default values are ...
1k views

### Returning an unevaluated expression with values substituted in

Let's say I have a function formula[x_List] := (x[[1]] - x[[2]]) + (x[[3]] - x[[4]]); and I want to pass it a variable and get back the unevaluated formula with ...
2k views

### How to generally match, unify and merge patterns?

This question was split from this one. While that question is now about how to match two particular patterns (mostly using Verbatim or ...
2k views

### Using Position (which requires a pattern) in the same manner as Select (which requires a criterion)

I am using Mathematica7. I have a list of lists (creatively named list in the following sample code) containing data. I would like to find the positions of the ...
2k views

### How is pattern specificity decided?

Mathematica has a notion of pattern specificity, which is a partial ordering on patterns. The rules (e.g. DownValues, SubValues,...
4k views

### Find zero crossing in a list

I'm looking for a function that finds the index of the zero-crossing points of a list. Before I go making my own subroutine to do this, I was wondering if anyone knows of any built-in Mathematica ...
689 views

### MatchQ-ing Associations (MMA 10)

Consider {x->1} which has FullForm List[Rule[x, 1]] and, therefore, ...
963 views

### Quick way to use conditioned patterns when defining multi-argument function?

I have a simple function that is supposed to only accept numeric values (i.e. complex/real numbers and constant symbols e.g. Pi, E). $$f(a,b,c)=a+b+c$$ Edit: I should have chosen a less simple ...
993 views

### Why is StringExpression faster than RegularExpression?

Edit: as noted by Albert Retey the performance difference is only seen when sub expression extraction is performed. If this test is used below the timings are similar: ...
2k views

### Find subexpression to minimize leafcount after replacment with temporary variable

Given an expression expr, is there an automated way to find a subexpression subexpr such that replacing ...
840 views

### Pattern matching multiple symbols names and powers

Seemingly a relatively simple problem, I can't seem to find a solution... I want to build a pattern that will match any symbol whose name starts with V, and is elevated at any power. Something on the ...
2k views

### Using ReplaceAll to replace a head

Why would this work to replace the head b with newHead: ...
6k views

### The difference between 0. and 0

I have a function for which 0 is a special case: f[A___, 0, B___] := 0 But since I am doing numerics, sometimes in the course ...
337 views

### Pattern matching on Orderless functions inside Hold

MatchQ[Hold[1 + 2], Hold[2 + 1]] returns False. But in the presence of a Blank[] in the ...
395 views

### Formatting text through pattern matching

I am trying to format some text based on some patterns. ...
2k views

### How to match a pattern with a pattern?

UPDATED This question is about: "What is the pattern to match a pattern-definition, exactly as it is written?" My original question is now split according to Mr.Wizards insightful answer below. This ...
1k views

### Specifying string patterns in DeleteCases

It seems that DeleteCases is not compatible with string patterns, at least directly (see, for example, this question). Is this true? If so, why is this the case? ...
483 views

### Recognizing special cases of a defined function for permuted arguments

I have a number of ugly ways to implement the following pattern recognition task, but I'm looking for something elegant to keep my notebook tidy. I need to define a function of six variables \$f(a,b,c;...
445 views

### Get the wrong result using the StringCase function and Shortest option

I have a list of strings like this ...
467 views

### Version inconsistency with optional arguments: what if the default value doesn't match the pattern?

I just came across some weird behaviour. Take this function definition: ClearAll[f] f[vs_List : All] := "match" The default value of ...
757 views

### How to match expressions with a repeating pattern

The expression I want to match obey a simple pattern that repeats it self a number of times. f[a]@f[b]@f[c]@...@f[X] How would you match all expressions of this ...
733 views

### How can I ensure that I am constructing patterns in the most efficient way possible?

Inspired by this answer, I am interested to know if there are best practices or rules of thumb for constructing patterns, for example for use in function definitions (...
1k views

### Pattern matching a pattern with patterns

Confusing title, I know. But the question is, if we have two patterns which have the same general structure but different names used in the patterns and different names: ...
514 views

### I can't use PatternSequence with Cases

I have a list of integers: s = {4, 5, 5, 6, 2, 5, 3, 2, 4, 2, 1, 1, 4, 3, 4, 3, 1, 6, 3, 4}; And if I do this, both occurrences of 4 after 3 are replaced. ...
432 views

### Pattern does not match with Orderless head

Why does the following pattern matching not succeed? ...
694 views

### Highlighting text with StringReplacePart but also using Style, Subscript

For a Natural Language Processing analysis task it's desirable to highlight a text string programmatically according to XML tags that reference specific words or phrases. The XML tags specify the ...
453 views

### Why is ReplaceAll behaving like this?

I'm learning to use the ReplaceAll function and I found the behavior of which is quite confusing. For Sqrt[f[x, y]] /. f[___] -> u Mathematica returns <...
426 views

### Orderless pattern matching

The MMA docs state that "In matching patterns with Orderless functions, all possible orders of arguments are tried". Why then does the following not work? ...
1k views

### Calling Table with custom iterator

I often find myself in situations where I, for example, need to build a table for some expression, but want to set the number of points rather then the step size, so the code ends up looking like this ...
317 views

### Strange behavior with Cases and Position with SetDelayed

I feel like I must be missing something simple and obvious here, but this has me scratching my head. This works as expected: ...
479 views

### The gap between MapAt and ReplacePart for 2D data tables with headers

Consider a relational table derived from survey data, where each column ("001-01" ...) represents a responder and each row (...
233 views

### How to achieve Set+Part like behaviour in custom Set function?

So I've been toiling away on my DataFrame package. I've been trying to get Set to work with it, but it seems it either can't be done (ie via ...
545 views

### Opposite of Alternatives

I was looking at this question (here) and I tried to find any thing gives the opposite of Alternatives. In other words, some pattern matching function that gives ...
301 views

### Why rule does not work if Flat attribute?

The following works: ...
156 views

### Pattern matching not going over a list when using default values

if I execute the following command in Mathematica: {a,a^2,a^3}/.a^(n_:1)->b^(2 n) Mathematica returns: {b^2,b^4,b^6} ...
3k views

### Fetching data from HTML source

I want to generate a couple of plots/graphs with Area 51 statistics. Since Area 51 doesn't work with the SE API, I'm forced to find another way to get the information I want. That other way is with <...
2k views

### Pattern to match a non-empty list of non-empty lists

Is there a pattern to match a list of lists, containing at least one list, with each list containing at least one element? In the Mathematica documentation it says that the pattern ...
924 views

### Position of a pattern-matched part of an expression

What you have A pattern, with certain part of it labeled As an example — Label: wally ...
3k views

### Match patterns on list of Strings

Consider the following: data={"AB","CD","AF"}; Now I would like to delete all String from data which starts with "A". Result:...
274 views

### How to get Cases to wrap results in an arbitrary head?

A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take Level...
542 views

### Pattern that matches colors

Suppose I'm writing a function that takes a color as a parameter; for example: drawShape[color_] := Graphics[{Style[Disk[], color]}]; But if the caller inputs an ...