Wednesday, November 20, 2013

Regex for Formatting a Number

A friend of mine sent me the code snippet below, containing a regex to format a number.  It uses positive look-ahead, which is why I'm putting it here.  I'm not very good with the positive look-ahead/look-behind, and I don't want to lose the example.

12500.to_s.gsub(/(?<=\d)(?=(?:\d{3})+\z)/, ',')
# => “12,500"

No comments:

Post a Comment