Split string into an array by comma, unless comma is inside quotes

The Ruby standard CSV library's .parse_csv, does exactly this.

require 'csv'
"\"hey, you\", 21".parse_csv
# => ["hey, you", " 21"] 

Yes, using CSV::parse_line or String#parse_csv, which require 'csv' adds to String's instance methods) is the way to go here, but you could also do it with a regex:

r = /
    (?:     # Begin non-capture group
    (?<=\") # Match a double-quote in a positive lookbehined
    .+?     # Match one or more characters lazily
    (?=\")  # Match a double quote in a positive lookahead.
    )       # End non-capture group
    |       # Or
    \s\d+   # Match a whitespace character followed by one or more digits
    /x      # Extended mode

str = "\"hey, you\", 21"
str.scan(r)
  #=> ["hey, you", " 21"]

If you'd prefer to have "21" rather than " 21", just remove \s.

Tags:

Ruby