José Ignacio Asked: 2020-11-28 13:18:32 +0800 CST 2020-11-28 13:18:32 +0800 CST 2020-11-28 13:18:32 +0800 CST How can I write a regular expression to find numbers with commas every three digits? 772 For example it must match: '42' '1,234' '6,368,745' And not with: '1234' (does not have commas) '12,34,567' (has only 2 digits between commas) regex 1 Answers Voted Best Answer abulafia 2020-11-28T13:37:13+08:002020-11-28T13:37:13+08:00 I think the following expression will work correctly in all cases: ^\d{1,3}(:?,\d{3})*$ At least in this demo it passes all the tests you have proposed. The expression reads like this: After the beginning of the string ( ^) there must be a group of between 1 and 3 digits ( \d{1,3}). Then optionally a non-capturing group (?:...)consisting of a comma and three other digits This last group can be repeated any number of times ( *). And after it, the end of the string ( $)
I think the following expression will work correctly in all cases:
At least in this demo it passes all the tests you have proposed.
The expression reads like this:
^
) there must be a group of between 1 and 3 digits (\d{1,3}
).(?:...)
consisting of a comma and three other digits*
).$
)