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?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityFrom 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}
{0, 0, 1, 0, 2} /. {0 ..., Shortest[x___]} :> {x}
$\endgroup$
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}
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 *)