Search code examples
javascriptregex

Regex to group numbers in threes excluding decimals


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.


Solution

  • If supported in your environment, you can make use of an infinite quantifier in a lookbehind assertion:

    \d{1,3}(?<!\.\d*)(?=(?:\d{3})*\b)
    

    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 boundary

    See a regex demo

    const regex = /\d{1,3}(?<!\.\d*)(?=(?:\d{3})*\b)/g;
    [
      "1123456789",
      "1123456789.999"
    ].forEach(s =>
      console.log(s.match(regex))
    )