user12283851
user12283851

Reputation: 55

Insert commas into a number through regex

I have a regex to insert commas in an integer:

(?<=\d)(?=(\d{3})+$)
1829383839 ==> 1,829,383,839

This regex is also covered by the question: Insert commas into number string

However, I'd also like to expand the regex to be able to do the commafication on decimal numbers. For example:

1829383839.2937484 ==> 1,829,383,839.2937484

How could this be done?

Upvotes: 2

Views: 2369

Answers (2)

The fourth bird
The fourth bird

Reputation: 163642

Another option could be to use (*SKIP)(*FAIL) to avoid matching the dot followed by digits.

\.\d+\b(*SKIP)(*FAIL)|\d{1,3}(?=(?:\d{3})+(?:\.\d|(?!\S)))

In parts

  • \.\d+\b Match a dot, 1+ digits and word boundary
  • (*SKIP)(*FAIL)| Match the characters that you want to avoid
  • \d{1,3} Match 1-3 digits
  • (?= Positive lookahead, assert what is on the right is
    • (?:\d{3})+ Repeat 1+ times matching 3 digits
    • (?: Non capturing group
      • \.\d Match a dot followed by a digit
      • | Or
      • (?!\S) Assert what is on the right is not a non whitespace char
    • ) Close non capturing group
  • ) Close lookahead

Regex demo

In the replacement use the full match followed by a comma $0,

Upvotes: 1

Toto
Toto

Reputation: 91518

Here is a way to go:

  • Find: (?:^|\G)(\d{1,3})(?=(\d{3})+(?:\.\d+)?$)
  • Replace: $1,

Explanation:

(?:^|\G)            # beginning of line or restart from last match posiiton
(\d{1,3})           # 1 to 3 digits
(?=                 # positive lookahead, make sure we have after:
    (\d{3})+            # 1 or more times 3 digits
    (?:\.\d+)?          # optional decimal places
    $                   # end of line
)                   # end lookahead

Demo & explanation

Upvotes: 4

Related Questions