Regex – Insert commas into number string


Hey there, I'm trying to perform a backwards regular expression search on a string to divide it into groups of 3 digits. As far as i can see from the AS3 documentation, searching backwards is not possible in the reg ex engine.

The point of this exercise is to insert triplet commas into a number like so:

10000000 => 10,000,000

I'm thinking of doing it like so:

string.replace(/(\d{3})/g, ",$1")

But this is not correct due to the search not happening from the back and the replace $1 will only work for the first match.

I'm getting the feeling I would be better off performing this task using a loop.


Due to AS3 not supporting lookahead this is how I have solved it.

public static function formatNumber(number:Number):String
    var numString:String = number.toString()
    var result:String = ''

    while (numString.length > 3)
        var chunk:String = numString.substr(-3)
        numString = numString.substr(0, numString.length - 3)
        result = ',' + chunk + result

    if (numString.length > 0)
        result = numString + result

    return result

Best Solution

If your language supports postive lookahead assertions, then I think the following regex will work:


Demonstrated in Java:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CommifyTest {

    public void testCommify() {
        String num0 = "1";
        String num1 = "123456";
        String num2 = "1234567";
        String num3 = "12345678";
        String num4 = "123456789";

        String regex = "(\\d)(?=(\\d{3})+$)";

        assertEquals("1", num0.replaceAll(regex, "$1,"));
        assertEquals("123,456", num1.replaceAll(regex, "$1,"));
        assertEquals("1,234,567", num2.replaceAll(regex, "$1,"));
        assertEquals("12,345,678", num3.replaceAll(regex, "$1,"));
        assertEquals("123,456,789", num4.replaceAll(regex, "$1,"));