Topic: Using a string as a regex pattern

Hi All,

I'm now at the stage of writing some Ruby code to import CSV files into my app.  The built in CSV libraries make this quite easy, but I'm having one problem.

During importation, I perform some transforms on individual cells in order to get the data into a suitable format.  For example:

if name == 'date'
  date_tokens = value.scan(/(\d+)\/(\d+)\/(\d+)/)[0]
  puts "Day: " + date_tokens[layout['date_day']]
  puts "Month: " + date_tokens[layout['date_month']]
  puts "Year: " + date_tokens[layout['date_year']]
end

That works nicely.  However, if I try to extract the pattern from the same layout information YAML file:

if name == 'date'
  date_tokens = value.scan(layout['date_pattern'])[0]
  puts "Day: " + date_tokens[layout['date_day']]
  puts "Month: " + date_tokens[layout['date_month']]
  puts "Year: " + date_tokens[layout['date_year']]
end

... then the match fails.  I'm guessing a string can't be used interchangably with a pattern here, but the API docs I've read aren't particularly clear on how to use search() with a string. 

Could anyone please point me at the relevant docs?  TIA :-)

Yours,
Duncan Bayne

Re: Using a string as a regex pattern

Try

   date_tokens = value.scan(Regexp.new(layout['date_pattern']))[0]

the date pattern in this case should NOT have enclosing slashes (i.e. /../).  Do this

Regexp.new('str')

not this

Regexp.new('/str/')

Look in Ruby pickaxe on page 601.

Last edited by willirl (2006-12-16 11:40:22)

Re: Using a string as a regex pattern

Thanks, worked a treat.  As I work through my current contract, I'm finding that all of the areas I'd flagged as potentially dangerous (in terms of slippage) are made easy by Rails.

One of the reasons I post so frequently here is that, given how easy it's proving, I want to make damn sure that I'm doing things the right way, not just the easy way - but again, the two are usually synonymous on Rails :-)

Thanks again for all the help :-)

Last edited by duncan_bayne (2006-12-17 00:28:16)