First, remove the spaces on either side of the commas:
If there might be spaces at the start or end of the line, get rid of them too.
Then you need to search for the comma separated elements ([^,]*),
- a sequence of zero or more not-commans, captured, followed by a space. to make a section optional, you wrap it in a non-capturing sequence and add a question mark (?:optional)?
. The result for 2-6 elements would be:
([^,]*),([^,]*)(?:,([^,]*)(?:,([^,]*)(?:,([^,]*)(?:,([^,]*))?)?)?)?
Which looks very complicated, but really is not, it is just the two elements above combined and nested.
([^,]*),([^,]*)
(?:
,([^,]*)
(?:
,([^,]*)
(?:
,([^,]*)
(?:
,([^,]*)
)?
)?
)?
)?
Add an up arrow and a $ to match the whole line and you're good to go.
You could make the expression deal with the spaces as well, by adding \s*
to the start and end and either side of every comma, and making the the pattern non-greedy ([^,]*?)
. But often with complex regular expressions it is simply easier to whittle, solving each part in turn, instead of trying to deal with a complex input.