0

In Ruby, what's a regular expression that identifies commas within quotes (e.g., "dog, cat, foo, bar")? My purpose is converting a CSV file to TSV, and some of my fields contain strings with commas within quotes that I want to preserve.

1
  • CSV files can play real havoc with a regex because of the potential for embedded commas inside fields. As @Doon suggested you're better off relying on a parser. Commented Dec 10, 2010 at 19:58

1 Answer 1

3

Does it have to be a regex? Can just Parse the CSV using your fav csv library, and then rejoin using tabs?

require 'csv'

 test = '"foo,bar,baz",one,two,three'
 CSV.parse_line(test).join("\t")

  "foo,bar,baz\tone\ttwo\tthree"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank ya, Doon! I ended up using FasterCSV::parse_line which worked as expected.
Converting a file (that doesn't contain tabs): CSV.read("temp.csv").map { |row| row.join("\t") }.join("\n").

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.