1

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?

2
  • It's not odd, it's just pipe-delimited values (like CSV with a | as a delimiter) Commented Aug 18, 2014 at 22:12
  • 1
    When you include an example in your question (which is generally helpful), it's a good idea to include your desired output, here ["APPROVED", "222222",..., "MC"], I assume. Commented Aug 18, 2014 at 22:39

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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"]

1 Comment

That's actually more of what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.