in reply to Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
in thread Using Regular Expressions to Simulate sprintf() function - One Liner Challenge

This is a regex exercise. There are many ways to do this, but I'm doing a discussion with some coworkers on regular expressions... Remember, we're trying to 'simulate' the sprintf() without actually using it.
  • Comment on Re: Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge

Replies are listed 'Best First'.
Re: Re: Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by Fastolfe (Vicar) on Nov 06, 2001 at 07:16 UTC
    s/(\d+(?:\.\d*)?|\d*\.\d+)/sprintf("%.2f", $1)/eg; # :)

    I really can't think of a way to do this in a pure regex. You've got some logic in there (like the addition of zeros where there aren't enough) that I can't think of a way to express in a regular expression while accomplishing the rest of your requirements, short of using program logic like above. Even if there is a solution, I suspect it will make use of Perl's advanced regular expression features and would thus be unportable to JavaScript.

    I'm interested in seeing if there are any good responses, though.