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

Why use a regex at all?
# perl $formatted = sprintf("%.2f", $unformatted); # javascript, assuming it doesn't have a s?printf() function formatted = Math.round(unformatted * 100) / 100;
  • Comment on Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
  • Download Code

Replies are listed 'Best First'.
Re: Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by Incognito (Pilgrim) on Nov 06, 2001 at 06:59 UTC
    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.
      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.