How can I define a regex that groups a number into threes excluding decimals?
Example
1123456789
-> ["1","123","456","789"]
1123456789.999
-> ["1","123","456","789"]
I’ve tried this Regex:
/d{1,3}(?=(d{3})*$)/g
But it outputs the following:
1123456789
-> ["1","123","456","789"]
1123456789.999
-> ["999"]
Edit: removed _
from the example strings.
4
Answers
Update to handle updated question
You could use any script that adds thousand separators, here I assume the number is smaller than MAXINT
Answers based on original question which was about
1_123_456_789
Just add the underscore to the regex (assuming there will always be an underscore) and use a negative lookbehind for the decimals
We then map to get the second part of the match, which is the group
Alternative
What happens is that the regex is set to find the end of the string, marked with the $. That is why it will return the numbers after the decimal only. If you want the oposite, make it start on the start of the string instead.
You should be able to use something like this –
to get your matches. It adds a digit search to the negative look-behind to get around matching digit strings that may occur AFTER the decimal
If supported in your environment, you can make use of an infinite quantifier in a lookbehind assertion:
The pattern in parts matches:
d{1,3}
Match 1-3 digits(?<!.d*)
Negative lookbehind to assert that the current match is not preceded by a dot and optional digits(?=(?:d{3})*b)
Positive lookahead, assert optional repetitions of 3 digits followed by a word boundarySee a regex demo