check if string starts with a timestamp in ruby

You can use a Regular Expression to check whether a string starts with a timestamp or not. A timestamp in the format of "hh:mm:ss" can be matched using the following regular expression:

main.rb
/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/
45 chars
2 lines

Here, ^ is the start-of-string anchor, which ensures that the timestamp is matched only at the beginning of the string. The pattern inside the parenthesis matches hours (00 to 23), minutes (00 to 59), and seconds (00 to 59) respectively. The ? after the 0 or 1 in the hour pattern allows matches of one or two digits.

You can use the match? method of the String class to test if a string matches this regular expression at the start of the string:

main.rb
string_to_check.match?(/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/)
69 chars
2 lines

This will return true if the string starts with a timestamp in the "hh:mm:ss" format, and false otherwise.

gistlibby LogSnag