Reputation: 678
I have a string which I need to parse in ruby, for example:
a = '"a,b","c,d","e,f"'
I'm using Postgres as a database, and using the below returns a different output.
# example:
a = '"a,b","c,d","e,f"'
a.split('"')
#=> ["", "a,b", ",", "c,d", ",", "e,f"]
The expected output is ["a,b" "c,d","e,f"]
Upvotes: 0
Views: 230
Reputation: 114268
Your string seems to contain comma separated values, so you could utilize Ruby's CSV library:
require 'csv'
CSV.parse_line('"a,b","c,d","e,f"')
#=> ["a,b", "c,d", "e,f"]
Upvotes: 1
Reputation: 110755
You can use String#split
with a regular expression for that.
str = '"a,b","c,d","e,f"'
#=> "\"a,b\",\"c,d\",\"e,f\""
arr = str.split(/(?<="),(?=")/)
#=> ["\"a,b\"", "\"c,d\"", "\"e,f\""]
puts arr
"a,b"
"c,d"
"e,f"
The regular expression reads, "match a comma preceded by a double quote ((?<=")
being a positive lookbehind) and followed by a double quote ((?=")
being a positive lookahead). (In fact, for the example given one need only include one of the positive lookarounds.)
Upvotes: 3