Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

書籍 Regular Expressions Cookbook | Validate Traditional Time Formats

パンくず

書籍 Regular Expressions Cookbook
Validate Traditional Time Formats

概要

時間のバリデーション。
hh:mi:ss
hh:24mi:ss
それぞれについて。

サンプル

subject = Array.new
subject << "11:11:11" # =>match
subject << "1:1:1" # =>match
subject << "09:09:09" # =>match
subject << "12:59:59" # =>match
subject << "00:00:00" # =>match
subject << "13:00:00"
subject << "12:60:00"
subject << "12:00:60"

pattern = /^(?:0\d|1[012]|\d):(?:[0-5][\d]|\d):(?:[0-5][\d]|\d)$/
subject.each_with_index {|each_subject,i|puts "#{i}:#{each_subject.scan(pattern)}"}

puts "------------------------------------------------------"

subject24 = Array.new
subject24 << "11:11:11" # =>match
subject24 << "1:1:1" # =>match
subject24 << "09:09:09" # =>match
subject24 << "12:59:59" # =>match
subject24 << "00:00:00" # =>match
subject24 << "00:00:00" # =>match
subject24 << "13:00:00" # =>match
subject24 << "23:59:59" # =>match
subject24 << "12:60:00"
subject24 << "12:00:60"

pattern24 = /^(?:0\d|1[\d]|2[0-3]|\d):(?:[0-5][\d]|\d):(?:[0-5][\d]|\d)$/
subject24.each_with_index {|each_subject,i|puts "#{i}:#{each_subject.scan(pattern24)}"}

結果

0:["11:11:11"]
1:["1:1:1"]
2:["09:09:09"]
3:["12:59:59"]
4:["00:00:00"]
5:[]
6:[]
7:[]
------------------------------------------------------
0:["11:11:11"]
1:["1:1:1"]
2:["09:09:09"]
3:["12:59:59"]
4:["00:00:00"]
5:["00:00:00"]
6:["13:00:00"]
7:["23:59:59"]
8:[]
9:[]