From: "Jesús Gabriel y Galán" Date: 2008-04-23T16:50:35+09:00 Subject: Re: Extract date from filenames using regex On Wed, Apr 23, 2008 at 9:14 AM, Clement Ow wrote: > Thanks Daniel for your input. I tried using /\d+/ but it'll extract > files that have even 2 numbers to i decided to use > /(\d\d)(\d\d)(\d\d\d\d)/ instead. It enabled me to run the command on > certain files but not all files and the following error occured: > > report_16042008.dat size: 77 KB > c:/ruby/lib/ruby/1.8/date.rb:1536:in `new_by_frags': invalid date > (ArgumentError > ) > from c:/ruby/lib/ruby/1.8/date.rb:1583:in `parse' > from testing.conf.rb:166:in `delFiles' > from testing.conf.rb:163:in `glob' > from testing.conf.rb:163:in `delFiles' > from testing.conf.rb:162:in `each' > from testing.conf.rb:162:in `delFiles' > from testing.conf.rb:204 > > Is there anything wrong with mycode that prevents deleting all the files > that I want? OK, now I see the problem. The file that is failing has a number like this: 16042008. The DateTime.parse method is trying to parse the date as: 1604-20-08 which is obviously an invalid date (month > 12). There are two solutions to this problem: 1.- Change DateTime.parse to DateTime.strptime passing a format that describes where in the string you have the two digits of the day, the month and the four digits of the date. I haven't been able to gather a quick example, cause I don't find a reference for the format string (any help here appreciated). The doc refers me to the date/format.rb for details and I don't see anything clear there. 2.- Change the regexp a little bit so you capture the day, the month and the year in separate groups and create the DateTime using the three values: irb(main):011:0> regexp = Regexp.compile(/(\d{4})(\d{2})(\d{2})/) => /(\d{4})(\d{2})(\d{2})/ irb(main):012:0> m = regexp.match("20080103asdfasdf") => # irb(main):014:0> d = DateTime.civil m[1].to_i, m[2].to_i, m[3].to_i => # irb(main):015:0> d.to_s => "2008-01-03T00:00:00+00:00" I think you can apply the above changes to the script and it will work. Let me know, Jesus.