ruby - How do I split a string by commas except inside parenthesis, using a regular expression? - Stack Overflow regex

PHOTO EMBED

Fri Aug 21 2020 20:20:59 GMT+0000 (Coordinated Universal Time)

Saved by @ludaley #rb

txt = "a,s(d,f(4,5)),g,h"
pattern = Regexp.new('((?:[^,(]+|(\((?>[^()]+|\g<-1>)*\)))+)')
puts txt.scan(pattern).map &:first




(                        # first capturing group
    (?:                  # open a non capturing group
        [^,(]+           # all characters except , and (
      |                  # or
        (                # open the second capturing group
           \(            # (
            (?>          # open an atomic group
                [^()]+   # all characters except parenthesis
              |          # OR
                \g<-1>   # the last capturing group (you can also write \g<2>)
            )*           # close the atomic group
            \)           # )
        )                # close the second capturing group
    )+                   # close the non-capturing group and repeat it
)                        # close the first capturing group
content_copyCOPY

https://stackoverflow.com/questions/18424315/how-do-i-split-a-string-by-commas-except-inside-parenthesis-using-a-regular-exp