Javascript Or Notepad++ Regular Expression To Add Thousands Separator To Arbitrary Text
As part of a visualisation, I'd like to add thousands separators to any numbers (contiguous string of digits) in a string. It needn't consider the context of the number e.g. 1234e+
Solution 1:
It's pretty much the same as your attempt, just reversed and with a quantifier:
\d(?=(?:\d{3})+(?!\d))
And replace that with $&,
.
The (?:\d{3})+
makes sure that there is a multiple of 3 digits following and the (?!\d)
then makes sure that there is no fourth or fifth digit following.
If you want to use this in Notepad++ make sure to upgrade to version 6.
Note that in Notepad++ you could also use a lookbehind:
(?<=\d)(?=(?:\d{3})+(?!\d))
And replace that with ,
.
Solution 2:
You could use this expression:
((?<=\d)\d{3}(?=\D|(?:\d{3})*(?:\D|$)))
And replace by ,$1
.
The lookbehind makes sure there's a number before the 3 digits we're matching.
The 3 digits we're matching are the 'thousands' you want to put a comma before.
The lookahead makes sure there's either a non-digit after, or a set of triplets of digits.
Post a Comment for "Javascript Or Notepad++ Regular Expression To Add Thousands Separator To Arbitrary Text"