Pattern matching for repeated elements
Use the Longest
pattern command to find the longest repeated sequence that matches the pattern.
l = {1, 2, 2, 2, 3, 4};
l /. {b___, x_, Longest[(x_) ..], r___} :> {b, r}
(*{1, 3, 4}*)
Try the following:
l = {1, 2, 2, 2, 3, 4};
l /. {b___, x_, (x_) .., r___} -> {{b}, {r}}
(* {{1}, {2, 3, 4}} *)
and you see that that r
is ill-defined. Therefore we must restrict r
:
l //. {b___, Repeated[x_, {2, 10}], Shortest@r___} :> {b, r}
(*{1, 3, 4}*)
Another possibility is to use SequenceReplace
:
SequenceReplace[{1, 2, 2, 2, 3, 4}, {x_, x_ ..} -> Sequence[]]
{1, 3, 4}