Reputation: 7576
I've got the following regex:
(\d{5}[,])
This matches the following:
12005,11111,11111,
but how do I make the trailing comma optional?
EDIT:
Acceptable results would be:
12005,
11111,11111,
12005
11111,11111
Unacceptable:
123456
123456,
12345,123456
123456,123456
Upvotes: 1
Views: 920
Reputation: 6721
to make sure you don't match 5 digits from numbers with 6 or more digits, use a word boundary assertion (\b
) and beginning of line assertion (^
), like so:
(?:\b|^)(\d{5})(?:,|$)
Upvotes: 1
Reputation: 120586
(\d{5})(?:,|$)
should do the trick.
To break this down,
\d{5}
- 5 digits(?:...)
- just using parentheses to surround the |
,
- a literal comma$
- end of input,|$
- a comma or end of input.The |$
part is needed to avoid spuriously matching groups of digits not separated by commas like "01234567889"
.
To see it in action, try
JSON.stringify(
["01234", "01234,", "01234,56789", "01234,56789", "", "0123456789"]
.filter(
function (s) {
return /^(?:(\d{5})(?:,|$))+$/.test(s);
}))
which uses a larger RegExp to match one or more of these groups, so emits
["01234","01234,","01234,56789","01234,56789"]
Upvotes: 5
Reputation: 14979
Perhaps this:
((?:\d{5},)*\d{5})
Will work if one set of 5 numbers or more than one separated by commas. Or you could get fully explicit and slap the start and end on it:
^((?:\d{5},)*\d{5})$
Upvotes: 1