Link to home
Start Free TrialLog in
Avatar of Rita Byrne
Rita ByrneFlag for Ireland

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.

Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

In what language (JavaScript, Python, C#, etc)?

HTH,
Dan
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:
(\d)(\d{3})((?:,\d{3})*)$

Open in new window

Replacement:
$1,$2$3

Open in new window

Demo:
https://regex101.com/r/rfE5IO/1
Avatar of Dr. Klahn
Dr. Klahn

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.


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
Avatar of louisfr
louisfr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rita Byrne

ASKER

Thanks for the replies.