1

I have a text document with a lot of large integers, e.g. 123456789. I want to automatically insert commas into these to make them more readable: 123,456,789. However, my document also contains decimals, and these should remain untouched. Is there a regular expressions that will insert these? An answer on a similar question suggested (?<=\d)(?=(\d\d\d)+(?!\d)), but this also detects decimal numbers. What's more, I am unable to insert the commas using either Notepad++ or Overleaf. What should I replace this regex with?

2 Answers2

0

If you don't want to touch the decimals you could use (*SKIP)(*FAIL) to match a dot and 1+ digits to consume the characters that should not be part of the match.

(Tested on Notepad++ 7.7.1)

\.\d+(*SKIP)(*FAIL)|\B(?=(?:\d{3})+(?!\d))

In the replacement use a comma ,

In parts

  • \.\d+(*SKIP)(*FAIL) Match a dot literally and 1+ digits (match to be left untouched)
  • | Or
  • \B Anchor that matches where \b does not match
  • (?= Positive lookahead, assert what is directly on the right is
    • (?:\d{3})+ Repeat 1+ times matching 3 digits
    • (?!\d) Negative lookahead, assert what is directly on the right is not a digit
  • ) Close lookahead

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
-1

My guess is that maybe,

(?<=\d)(?=(?:\d{3})+(?!\d|\.))

or

(?!^)(?=(?:\d{3})+(?!\.|\d))

Demo 2

or

\d+\.\d*(*SKIP)(*FAIL)|(?!^)(?=(?:\d{3})+(?!\.|\d))

Demo 3

might be close to what you're trying to write, which you can simply replace it with a comma.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Thanks for your reply! Unfortunately, this also puts commas at the left endpoint, like ```,345```, or ```34.,345```. Do you know a workaround for this? –  Sep 24 '19 at 00:17