# What is the proper way to the pattern form Repeated in my code?

I'm matching a pattern with Repeated (..) How can I use the repeat count in the replacement rule?

Example:

 Cases[ { {0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}} ,
{0, Repeated[x_ /; x != 5], 5, __} :> {0, Sequence @@ Table[x, {2}], 5}]
^ <---?


{{0, 2, 2, 5}}

Obviously instead of hard coding the 2 I want the length of the repeat..

My workaround for this example is this:

 #[[;; First@First@Position[#, 5]]] & /@
Cases[ { {0, 2, 2, 5, 2, 4, 1, 2}, {0, 5, 5, 1, 2, 3, 4, 5}} ,
{0, Repeated[x_ /; x != 5], 5, __} ]


{{0, 2, 2, 5}}

It seems there should be a cleaner solution though.

-
Use named patterns: Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}}, {0, rep : Repeated[x_ /; x != 5], 5, __} :> {0, rep, 5}]. – Leonid Shifrin Apr 25 '14 at 16:00
Thanks! Maybe this should be closed if you think it too simple. – george2079 Apr 25 '14 at 16:05
I don't have a strong opinion here. It may be simple for those who used this many times, but I bet many people might have such questions. And, the fact that a 5K rep user bothered to ask it may mean that it is not trivial at the very least. Let's wait what others think. – Leonid Shifrin Apr 25 '14 at 16:06
On second thought, I actually think we should keep this one - it is a nice example of more complex patterns, where one really does need two pattern variables, one for the entire pattern and another one to restrict its parts. – Leonid Shifrin Apr 25 '14 at 16:53

Just so this doesn't sit unanswered, per @LeonidShifrin comment:

 Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}},
{0, rep : Repeated[x_ /; x != 5], 5, __} :> {0, rep, 5}]


or : {0, rep : x_ .. /; x != 5 , 5, __}

For completeness if you literally wanted to use the form in the question:

 Cases[{{0, 2, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}},
{0,rep : Repeated[x_ /; x != 5], 5, __} :>
{0,Sequence @@ Table[ x, {Length@List@rep}], 5}]

-
so as not to give readers the impression that Repeated picks out the sub-expression ,2,2,  because it contains repeated two's, it might be useful to generalise to: Cases[{{0,2,2,5,2,4,1,2},{0,1,2,3,4,5}},{0,pat: x_ ..,y_,__}:>{0,pat,y}/;Length[{pat}]>1] or, in alternative form: Cases[{{0, 2, 2, 5, 2, 4, 1, 2}, {0, 1, 2, 3, 4, 5}}, {0, rep : Repeated[x_ /; x != 5, {2, \[Infinity]}], y_, __} :> {0, rep, y} ] – Wouter Apr 26 '14 at 17:11
for my application I intended the basic "one or more" meaning of Repeated – george2079 Apr 28 '14 at 19:20