To deal with nested brackets, you can use:
txt = "a,s(d,f(4,5)),g,h" pattern = Regexp.new('((?:[^,(]+|(\((?>[^()]+|\g<-1>)*\)))+)') puts txt.scan(pattern).map &:first
more details:
(
The second capture group describes a nested parenthesis that may contain characters that are not parentheses or the capture group itself. This is a recursive pattern.
Inside the template, you can refer to the capture group with its number ( \g<2> for the second capture group) or with its relative position ( \g<-1> first to the left of the current position in the template) (or with its name, if you use named capture groups)
Note. You can enable a single bracket by adding |[()] to the end of a non-capturing group. Then a,b(,c will give you ['a', 'b(', 'c']
source share