Reputation: 12520
Given a string of an array in Ruby with some items in quotes that contain commas:
my_string.inspect
# => "\"hey, you\", 21"
How can I get an array of:
["hey, you", " 21"]
Upvotes: 6
Views: 2314
Reputation: 110685
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
.
Upvotes: 3
Reputation: 12520
The Ruby standard CSV library's .parse_csv
, does exactly this.
require 'csv'
"\"hey, you\", 21".parse_csv
# => ["hey, you", " 21"]
Upvotes: 7