9
$\begingroup$

This functions and gives the desired result:

{1, 0, 2, 0, 0} /. {x___, 0 ...} :> {x}

{1, 0, 2}

But with leading zeros it doesn't:

{0, 0, 1, 0, 2} /. {0 ..., x___} :> {x}

{0, 0, 1, 0, 2}

Why is that so? Is there a workaround?

$\endgroup$
14
$\begingroup$

From the docs of Longest:

The default is to have earlier patterns match shortest sequences

Therefore, use Longest for the zeros:

{0, 0, 1, 0, 2} /. {Longest[0 ...], x___} :> {x}

{1, 0, 2}

$\endgroup$
  • 4
    $\begingroup$ Or {0, 0, 1, 0, 2} /. {0 ..., Shortest[x___]} :> {x} $\endgroup$ – andre314 Oct 17 '15 at 11:31
1
$\begingroup$

Considering the efficiency,I will not use Pattern Match,this recommand a function Internal`DeleteTrailingZeros,which is intend to delete those zeros in tail.As your case:

Reverse[Internal`DeleteTrailingZeros[Reverse[{0, 0, 1, 0, 2}]]]

{1, 0, 2}

$\endgroup$
0
$\begingroup$

a slight modification of the accepted answer:

{0, 0, 1, 0, 2, 0, 0} /. {Longest[0 ...], x___, 0 ...} :> {x} (* works with both leading and trailing zeros *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.