Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating string using ruby Reg Expressions?

Tags:

regex

ruby

how can i validate that the date and time in the following string is in the right format i.e year, month, day and then the time(4 digits, 2 digits, 2 digits and then the time)

"Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )"

thanks

like image 853
Mo. Avatar asked Dec 23 '22 01:12

Mo.


2 Answers

Why create your own regular expressions when Ruby can handle the parsing for you?

>> require 'date'
 => true

>> str = "Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )"
>> dt = DateTime.parse(str)
 => #<DateTime: 2010-04-27T11:48:00-08:00 (98212573/40,-1/3,2299161)> 

This also makes sure the date is valid, not just in a recognizable format:

>> str = "Event (No 3) 0007141706 at 2010/13/32 25:61 ( Pacific )"
>> dt = DateTime.parse(str)
ArgumentError: invalid date
like image 152
Lars Haugseth Avatar answered Jan 02 '23 17:01

Lars Haugseth


/Event \(No \d+\) \d+ at (\d{4})\/(\d{2})\/(\d{2}) (\d\d):(\d\d) \([\w\s]+\)/
like image 29
Amarghosh Avatar answered Jan 02 '23 16:01

Amarghosh