Regexdrill

Level 5: Advanced Exercise 79 of 88 Free

Lookahead: thousands separators

A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.

The task

Each line is one whole number. Insert a comma between every group of three digits, counting from the right, so 1234567 becomes 1,234,567. Numbers with fewer than four digits stay unchanged.

What this exercise teaches

\B(?=(\d{3})+(?!\d)) matches the empty position where the digits to its right can be split into groups of three all the way to the end. \B keeps the start of the number out, so 123456 does not get a leading comma. This is a classic interview question; in real code Intl.NumberFormat or toLocaleString does the job.

A hint if you get stuck

Match positions, not characters: a spot inside the number, \B, that is followed by one or more groups of exactly three digits and then no further digit. Replace that empty spot with a comma.

Try it now, free, no account needed

Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Advanced