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

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.

  • Comment on Re: Re: Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
  • Download Code