Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Regular Expressions Cookbook | Validate Traditional Date Formats

パンくず

書籍 Regular Expressions Cookbook
Validate Traditional Date Formats

概要

日付のバリデーション。
YYYY-MM-DD
もしくは
YYYY/MM/DD
かつ
MMは01-12で一桁の場合は0を省略可能。
DDは01-31で一桁の場合は0を省略可能。

この条件にマッチする正規表現を作成します。

サンプル

subject = Array.new
subject << "2012/01/30" # =>match
subject << "2012/1/1" # =>match
subject << "2012/01/01" # =>match
subject << "2012/01/29" # =>match
subject << "2012/11/30" # =>match
subject << "2012-11-30" # =>match
subject << "20121130"
subject << "2012/12/32" # =>match
subject << "2012/13/30"
subject << "12012/12/30"
pattern = /^(?:[\d]{4}[\/-](?:1[12]|0?[\d])[\/-](?:[0-2][\d]|3[01]|\d))/
subject.each_with_index {|each_subject,i|puts "#{i}:#{each_subject.scan(pattern)}"}

結果

0:["2012/01/30"]
1:["2012/1/1"]
2:["2012/01/01"]
3:["2012/01/29"]
4:["2012/11/30"]
5:["2012-11-30"]
6:[]
7:["2012/12/3"]
8:[]
9:[]