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.
UPDATE:
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 }
If your language supports postive lookahead assertions, then I think the following regex will work:
Demonstrated in Java: