The solution is to anchor every group separately, like so: (^\d+,\d+[acd]\d+,\d+$)|(^\d+[acd]\d+,\d+$)|(^\d+,\d+[acd]\d+$)|(^\d+[acd]\d+$)