Validating a string using Ruby Reg Expressions?

how can I check that the date and time in the next line are in the correct format ie year, month, day, and then time (4 digits, 2 digits, 2 digits, and then time)

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

thanks

+4
source share
3 answers
 if "Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )" =~ /\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}/ puts "Date and time found." end 

This will check if your string contains date and time in the specified format.

However, it only checks the number of digits, so the line containing 2010/13/99 93:71 will be the same. It is not so.

+2
source

Why create your own regular expressions when Ruby can handle 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)> 

It also ensures that the date is valid, and 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 
+6
source
 /Event \(No \d+\) \d+ at (\d{4})\/(\d{2})\/(\d{2}) (\d\d):(\d\d) \([\w\s]+\)/ 
+3
source

Source: https://habr.com/ru/post/1314063/


All Articles