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 exerciseMore exercises in Advanced
- Lookahead: amounts before USDFree
- Lookahead: mask all but the last four digitsFree
- Lookahead: strip leading zerosFree
- Negative lookahead: not starting with unFree
- Negative lookahead: lines without a wordFree
- Lookbehind: amounts after $Free
- Negative lookbehind: positive numbers onlyFree
- Lazy vs greedy: the first quoted textFree
- Named groups: year, month, dayFree
- Password rules with lookaheadsFree
- Word boundaries: replace a whole wordFree
- Unicode letters with the u flagFree
- Multiline flag: TODO linesFree
- The s flag: comments that span linesFree
- Backreference across lines: duplicate linesFree
- Multiline: trailing whitespace on every lineFree
- Named groups in a replacementFree
- Multiline anchors: lines ending in a semicolonFree
- Negative lookahead: numbers that are not percentagesFree