Reputation: 81
I need a regex to match and extract all the values from a comma separated list. The maximum size of the list is always the same.
For example the if max size is 3 the following lists can exist:
VALUE1,VALUE2,VALUE3
VALUE1,VALUE2
VALUE1
I need, if possible, a regex to extract in capturing groups the elements above, no matter of what list is given as input.
I have tried with something simple like:
(.*)(,?)(.*)(,?)(.*)
But it matches the whole thing, no values are extracted. I don't understand why the ?
doesn't work correctly in this case.
What I need: to apply the same regex for all the lists and extract the values.
Given the regex is used (.*)(,?)(.*)(,?)(.*)
Given the input list is VALUE1,VALUE2,VALUE3
Then I expect that group1=VALUE1, group3=VALUE2, group5=VALUE3
Given the regex is used (.*)(,?)(.*)(,?)(.*)
Given the input list is VALUE1,VALUE2
Then I expect that group1=VALUE1, group3=VALUE2
Given the regex is used (.*)(,?)(.*)(,?)(.*)
Given the input list is VALUE1
Then I expect that group1=VALUE1
Upvotes: 1
Views: 1247
Reputation: 189799
You can make some of the groups optional, and simplify slightly by avoiding parentheses where they are unnecessary. You should also make your regex unambiguous; .*
can match a comma, and the regex engine will do that if it needs to do that in order to find a match. You will also want to add anchors to the expression to avoid matching a substring of a longer line.
^([^,]*)(,([^,]*)(,([^,]*))?)?$
Demo: https://regex101.com/r/swUn3B/2
(where I had to add \n
to the character class [^,\n]
to avoid straddling newlines in the test data).
The fundamental problem with your attempt is that ,?
is allowed to match nothing, and so the regex engine will do that if it's needed to achieve a match. The trick in this solution is to only make the entire group optional: if there is no comma, that's fine; but if there is a comma, it needs to be followed by another group of non-comma characters. We repeat this as many times as necessary to capture the specified maximum number of non-comma groups.
Upvotes: 1