Reputation: 45
An API responds with a string such as the following.
"\"APPROVED\"|\"222222\"|\"11111111\"|\"\"|\"M\"|\"\"|\"5454\"|\"MC\""
I was using the following code to parse
str = str.scan(/\w+/)
This worked fine, as I could str[0], str[1], etc..
Than a response such as
"\"DECLINED\"|\"\"|\"64243178\"|\"\"|\"\"|\"\"|\"Invalid Exp Date\"|\"\"|\"5454\"|\"MC\""
Trying to parse Invalid Exp Date ends up with simply
str[2] => Invalid
I tried the following
str.split("\"|")
But there is always a quote in the beginning
"Invalid Exp Date
"APPROVED
What is the best way to parse such a string?
Upvotes: 1
Views: 61
Reputation: 434585
I'd probably use the standard CSV parser for this, for example:
> s = "\"APPROVED\"|\"222222\"|\"11111111\"|\"\"|\"M\"|\"\"|\"5454\"|\"MC\""
> CSV.parse(s, :col_sep => '|')
=> [["APPROVED", "222222", "11111111", "", "M", "", "5454", "MC"]]
CSV covers more than just Comma Separated Values, a pipe is just as good a separator as a comma.
Upvotes: 4
Reputation: 110665
This is a straightfoward solution using String#gsub and String#split:
s = "\"APPROVED\"|\"222222\"|\"11111111\"|\"\"|\"M\"|\"\"|\"5454\"|\"MC\""
s.gsub('"','').split('|')
#=> ["APPROVED", "222222", "11111111", "", "M", "", "5454", "MC"]
Upvotes: 0