Regex reads from right to left

It isn't actually reading right-to-left. What's really happening is that it's repeatedly applying the (\d+)(\d{3}) pattern (via a while loop) and replacing until it no longer matches the pattern. In other words:

Iteration 1:

x1 = 83475934.89
x1.replace((\d+)(\d{3}), '$1' + ',' + '$2');
x1 = 83475,934.89

Iteration 2:

x1 = 83475,934.89
x1.replace((\d+)(\d{3}), '$1' + ',' + '$2');
x1 = 83,475,934.89

Iteration 3:

x1 = 83,475,934.89
x1.replace((\d+)(\d{3}), '$1' + ',' + '$2');
// no match; end loop

Edit:

Plus, what does $1 and $2 mean?

Those are back references to the matching groups (\d+) and (\d{3}) respectively.

Here's a great reference for learning how Regular Expressions actually work:
http://www.regular-expressions.info/quickstart.html


It matches from right to left because it uses greedy pattern matching. This means that it first finds all the digits (the \d+), then tries to find the \d{3}. In the number 2421567.56, for example it would first match the digits up until the '.' - 2431567 - then works backwards to match the next 3 digits (567) in the next part of the regex. It does this in a loop adding a comma between the $1 and $2 variables.

The $'s represent matching groups formed in the regex with parentheses e.g. the (\d+) = $1 and (\d{3}) = $2. In this way it can easily add characters between them.

In the next iteration, the greedy matching stops at the newly created comma instead, and it continues until it can't match > 3 digits.