Ferdy
Ferdy

Reputation: 678

String parsing in ruby

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

Answers (2)

Stefan
Stefan

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

Cary Swoveland
Cary Swoveland

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

Related Questions