From: James Gray Date: 2009-06-22T21:49:24+09:00 Subject: Re: if column header contain regexp, delete column On Jun 21, 2009, at 9:14 PM, Paul Shapiro wrote: > James Gray wrote: >> On Jun 21, 2009, at 3:15 PM, Paul Shapiro wrote: >> >>>>> the rio and fastercsv gems. The fastercsv documentation has been >>>> delete a column of CSV. Can you tell me why it's failing?" for >>>> I hope that helps. >>>> >>>> James Edward Gray II >>> >>> Ok. I would like to use fastercsv with maybe delete_if(&block) or >>> delete(index_or_header), where the index is selected by a regular >>> expression match. >> >> Awesome. That helped. Thanks. >> >> I would probably try something like this: >> >> $ cat data.csv >> A,B,C,D >> 1,2,3,4 >> 5,6,7,8 >> $ cat del_col.rb >> #!/usr/bin/env ruby -wKU >> >> require "rubygems" >> require "faster_csv" >> >> table = FCSV.table("data.csv") >> table.headers.each do |h| >> next unless h.to_s =~ /\A[bd]\z/i >> table.delete(h) >> end >> puts table >> >> __END__ >> $ ruby del_col.rb >> a,c >> 1,3 >> 5,7 >> >> Hope that helps. >> >> James Edward Gray II > > Alright. I'm not getting this to work. I'm doing this: > > table = FCSV.table("/Users/pshapiro/Desktop/Excel/csv/Attention.csv") > table.headers.each do |h| > next unless h.to_s =~ /(S[0-9]+\s\b)/ > table.delete(h) > end > puts table > > The regexp im using is "(S[0-9]+\s\b)" to match "S31 Which best > describes how you answered the online reading comprehension quiz?" > > I'm not sure if its a problem with my ruby syntax or an incorrect > regexp? It's FasterCSV kind of cheating you a little bit here. The table() method uses some options to make it as easy as possible to programmatically work with the resulting data structure. One of those options turns the headers into Symbols, so your header really ends up looking like: :s31_which_best_describes_how_you_answered_the_online_reading_comprehension_quiz Thus the Regexp needs to be adapted accordingly. Here's one you might try: /\AS\d+/i Hope that helps. James Edward Gray II