Well, you need to get a regex that identifies complete groups of three digits before the decimal point, so you can copy them with a prepended comma symbol. But the problem is that you can control only the match with the regular expression, and not the substitution pattern (that varies in case your pattern matches several groups or not)
The first attempt is to try to match \d?\d?(\d\d\d)*(\.\d*\|\b)
(one or two digits, followed by zero or more groups of three digits ---this is what we are interested in) followed by either a decimal point with more digits (we are not interested on these, as we are not goint to substitute any of them) or a word boundary (to disallow matching sequences with several points like (e.g. 012345.2342.1233)
The problem is that we have only one group of interest here (the central (\d\d\d)
) but that means we have to construct the substitution pattern with all the rest and put the group somewhere (so our regexp changes to (\d?\d?)(\d\d\d)*(\.\d\|\b)
so we can use \1,\2\3
as the substitution). That is incorrect, because we'll put only a comma in front of the last group matched as \2
and wee need to do a substitution for each matching group.
The next approach is to use several groups explicitly in the regexp, like (\d?\d?)(\d\d\d)?(\d\d\d)?...(\d\d\d)?(\.\d*\|\b)
, so we can substitute each group (\2
, \3
... with ,\2
, ,\3
...) but this also doesn't work, as you will put always the commas, in their places, independent of the matching of the internal groups (giving you something like 1,,,,000,000,000.234566
. Of course, you can do a two step approach, making two substitutions: the last one, and one that changes ,,+
into ,
(multiple comma sequences into a single comma)
The only approach then is to actually match \d\d\d
, and substitute the match by ,\0
. But this time we run into trouble again, as we must have the whole digit string, as the groups begin in the end, and this is context information that we need to isolate from our regular expression.
The only solution that works is to identify the string that matches the digit sequence of interest (the digit strings not preceded by a dot and with more than three digits, e.g. (^\|[^.\n])(\d\d\d\d*)
and then do all the substitution on them. Beware, that as you have to begin on the right and go to the left, you have to do it once (searching for the last group of three digits \d\d\d$
and change it to ,\0
)
As it has been suggested in one of the answers to the question you refer to in yours, the best way is to use an alternate method, like this (using toLocaleString()
javascript method)