lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 8/30/13, Geoff Smith <spammealot1@live.co.uk> wrote:
> I am trying to trim a number string to remove non significant trailing
> zeros. So for example
>
> "123.450000000" = "123.45"
> "1234500" = "1234500"
> "12345.00" = "12345.0"

> Can this be done neatly with pattern matching ?

Hi Geoff,

Will the strings you are matching always contain just the number and
only the number? If so, here is my suggestion:

 function trim_trailing_zeros(str)
   local v = string.gsub(str, '(%.%d%d-)0+$', '%1')
   return v
 end

I'll break down the pattern for you a bit:
  The parentheses '('..')' select part of the match to capture. Here
we are capturing everything from the decimal point up to, but not
including, the trailing zeros.
  '%.' matches the decimal point. We need the % here because just a
dot on its own has special meaning in string patterns.
  '%d' matches the first 0-9 digit immediately after the decimal
point. This part of the pattern is here is so that, for example,
"0.0000" will become "0.0", not "0."
  '%d-' matches any number of 0-9 digits -- but will capture as FEW as
possible -- it's important to specify this because otherwise it could
match some of the trailing zeros that we are trying to split off
  '0+' matches one or more zeros.
  '$' matches only at the end of the string.

So, using string.gsub() with this pattern means we match it as many
times as possible, but since this particular pattern can only ever
match at the end of the string, "as many times as possible" will
either be once or not at all. The third argument to gsub, "%1", means
that where there is a match, we want to replace the matched part of
the string with the first capture, which as noted earlier is
everything from the decimal point up to but not including the trailing
zeros.

-Duncan