Repeated Patterns

Repeated patterns.

Multiple blanks such as x__ allow you to give patterns in which sequences of arbitrary expressions can occur. The Wolfram Language pattern repetition operators .. and ... allow you to construct patterns in which particular forms can be repeated any number of times. Thus, for example, f[a..] represents any expression of the form f[a], f[a,a], f[a,a,a], and so on.

The pattern f[a..] allows the argument a to be repeated any number of times:

Cases[{f[a],f[a,b,a],f[a,a,a]},f[a..]]

This pattern allows any number of a arguments, followed by any number of b arguments:

Cases[{f[a],f[a,a,b],f[a,b,a],f[a,b,b]},f[a..,b..]]

Here each argument can be either a or b:

Cases[{f[a],f[a,b,a],f[a,c,a]},f[(a|b)..]]

You can use .. and ... to represent repetitions of any pattern. If the pattern contains named parts, then each instance of these parts must be identical.

This defines a function whose argument must consist of a list of pairs:

v[x:{{_,_}..}]:=Transpose[x]

The definition applies in this case:

v[{{a1,b1},{a2,b2},{a3,b3}}]

With this definition, the second elements of all the pairs must be the same:

vn[x:{{_,n_}..}]:=Transpose[x]

The definition applies in this case:

vn[{{a,2},{b,2},{c,2}}]

The pattern x.. can be extended to two arguments to control the number of repetitions more precisely.

Controlling the number of repetitions.

This finds from two to three repetitions of the argument a:

Cases[{f[a],f[a,a],f[a,a,a],f[a,a,a,a]},f[Repeated[a,{2,3}]]]