How do I split a string by commas except inside parenthesis, using a regular expression?

后端 未结 2 420
天命终不由人
天命终不由人 2020-12-17 02:29

I want to split a string by comma:

\"a,s\".split \',\'  # => [\'a\', \'s\']

I don\'t want to split a sub-string if it is wrapped by par

2条回答
  •  春和景丽
    2020-12-17 02:41

    Assuming that parentheses are not nested:

    "a,s(d,f),g,h"
    .scan(/(?:\([^()]*\)|[^,])+/)
    # => ["a", "s(d,f)", "g", "h"]
    

提交回复
热议问题