How can I build a regular expression that will match a string of any length containing any characters but which must contain 21 commas?
If you're using a regex variety that supports the Possessive quantifier (e.g. Java), you can do:
^(?:[^,]*+,){21}[^,]*+$
The Possessive quantifier can be better performance than a Greedy quantifier.
Explanation:
(?x) # enables comments, so this whole block can be used in a regex.
^ # start of string
(?: # start non-capturing group
[^,]*+ # as many non-commas as possible, but none required
, # a comma
) # end non-capturing group
{21} # 21 of previous entity (i.e. the group)
[^,]*+ # as many non-commas as possible, but none required
$ # end of string