From: G_ F_ <8si.greg@...> Date: 2009-09-08T01:56:06+09:00 Subject: Re: Date & time validation Ne Scripter wrote: > Just an update of where I am. This is what I have > > if date =~ (/\d{4}\/\d{2}\/\d{2}/) > puts date > else > date = (Date.strptime(date, "%Y/%m/%d")) > end > > This works to an extent but does not deal with a string which contains a > valid date but still invalid data like so > > 2009/09/07 12:12:12 > > This would be passed as valid when it is not only a string containing > yyyy/mm/dd. Ok, to summarize to see if I've got it right: blah 2009/09/07 blah # <-- is what we want to accept blah 2009/09/07 12:00:00 blah # <-- is what we want to reject %r#\d{4}/\d{2}/\d{2}# matches a date but gives a false positive for dates followed by time. You could filter out lines that have date followed by time using something like: next if %r#\d{4}/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}# then capture any that make it past that test with a regular date regex. Or, you can combine the test and capture in one regex pattern using look-ahead... %r#(\d{4}/\d{2}/\d{2})\s+(?!\d{2}:\d{2}:\d{2})# =~ 'blah 2009/01/01 blah' # => 5 %r#(\d{4}/\d{2}/\d{2})\s+(?!\d{2}:\d{2}:\d{2})# =~ 'blah 2009/01/01 12:00:00 blah' # => nil The first line successfully matches "text date text". The second line rejects "text date time text". -- Posted via http://www.ruby-forum.com/.