http://www.perlmonks.org?node_id=640204


in reply to When greedy constructs do battle, can I choose the winner?

It sounds like you just want to make {1,5} not greedy to me.

$running_total =~ s/(\d{1,5}?)0*$/$1/;
Is this what you want?

update: Looking at your question again, perhaps your problem is also that you're doing a substitution (which I just parroted) and you really want to do something more like this:

$running_total = $1 if $running_total =~ /(\d{1,5}?)0*$/;

Replies are listed 'Best First'.
Re^2: When greedy constructs do battle, can I choose the winner?
by amarquis (Curate) on Sep 20, 2007 at 18:35 UTC

    For a number such as 243210890000, the non greedy {1,5} grabs the least it can, the 9, correct? I do want the {1,5} to grab as many as it can, up to 5 digits, but I don't want it grabbing any of the trailing zeros. Examples of what I want:

    Input $1 28400300 84003 100 1

    As it stands, if the input is "10" the {1,5} grabs itself some zeros, and I want those zeros to go into the 0* (I don't want 'em captured).

    I've rewritten the regex so that it matches "(zero to four digits, one non-zero digit) and then the 0*" but the issue got me curious to see if there was some way you could make the right-most greedy construct "beat out" one to its left.

      For a number such as 243210890000, the non greedy {1,5} grabs the least it can, the 9, correct?

      Incorrect. The string is processed left to right, so the non-greedy {1,5} will match one character then try to match zeroes to the end of the string. Since this fails the overall match, the RE engine will backtrack and try two characters, then three and four and five. When the five character version fails, backtracking will cause the starting point of the {1,5} match to move over one character and try again. This continues until either there's a match or the RE engine determines that it can't match.