Rita Byrne
asked on
Reg Ex
I'm looking to create a Reg Ex for put commas into numbers after thousands to make it more legible. For example, the user enters 1234567 and I want to display 1,234,567.
Any help appreciated.
Unless you're using specific regex tools that allow replacement string conditionals, you'll need to repeat a replacement regex until no more matches are found. If you repeat the following, it should do the job:
Pattern:
https://regex101.com/r/rfE5IO/1
Pattern:
(\d)(\d{3})((?:,\d{3})*)$
Replacement:$1,$2$3
Demo:https://regex101.com/r/rfE5IO/1
This is not a good application for a regex. It can be done per Terry's example above, but it's clunky.
Most programming languages include thousands separator support in the output / format translation routines, e.g. printf in C with the %'d formatter. As a bonus, in linux the ' formatter is dependent on the locale and uses either full stop or comma as appropriate.
Finally, if the language offers no support at all, write your own reformatter like the one below and you won't need to worry about how many capture groups were captured, or which ones.
So: 7846263
Push to stack 7, 8, 4, 6, 2, 6, 3
Unstack 3, 6, 2 -> 263
Add comma -> ,
Unstack 6, 4, 8 -> 846,263
Add comma -> ,846,263
Unstack 7 -> 7,648,263
Most programming languages include thousands separator support in the output / format translation routines, e.g. printf in C with the %'d formatter. As a bonus, in linux the ' formatter is dependent on the locale and uses either full stop or comma as appropriate.
Finally, if the language offers no support at all, write your own reformatter like the one below and you won't need to worry about how many capture groups were captured, or which ones.
convert binary number to decimal characters
push characters on stack
until stack is empty
if more than three characters remain
unstack three characters reversed to output buffer
add comma to output buffer
else
unstack remainder reversed to output buffer
So: 7846263
Push to stack 7, 8, 4, 6, 2, 6, 3
Unstack 3, 6, 2 -> 263
Add comma -> ,
Unstack 6, 4, 8 -> 846,263
Add comma -> ,846,263
Unstack 7 -> 7,648,263
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the replies.
HTH,
Dan