正则表达式能以非常 concise 的形式表达复杂的逻辑,不过复杂的表达式难写、难读,比如下面这个匹配日期的正则表达式:
/\A((?:19|20)[0-9]{2})[\- \/.](0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])\z/
用/x
换成多行模式后可读性稍微好一点:
/\A((?:19|20)[0-9]{2})[\- \/.] #年
(0[1-9]|1[012])[\- \/.] # 月
(0[1-9]|[12][0-9]|3[01])\z #日
/x
而用了re 模块之后,无论是写起来,还是读起来,都很容易:
require 're'
include Re
delim = re.any("- /.")
century_prefix = re("19") | re("20")
under_ten = re("0") + re.any("1-9")
ten_to_twelve = re("1") + re.any("012")
ten_and_under_thirty = re.any("12") + re.any("0-9")
thirties = re("3") + re.any("01")
year = (century_prefix + re.digit.repeat(2)).capture(:year)
month = (under_ten | ten_to_twelve).capture(:month)
day = (under_ten | ten_and_under_thirty | thirties).capture(:day)
date = (year + delim + month + delim + day).all
代码变长了,但是每个部分都很短小,也很容易验证。同时,捕获的部分可以通过相应的变量名访问:
result = date.match("2009-01-23")
result[:year] # => "2009"
result[:month] # => "01"
result[:day] # => "23"