这里有一些替代方法来做你想做的事,这就是我的做法:
s = "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:<br>\nAny Network Cap remaining: $366.550<br>International Cap remaining: $0.000" # => "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:<br>\nAny Network Cap remaining: $366.550<br>International Cap remaining: $0.000"
dt1, dt2 = /period (\S+ \S+) to (\S+ \S+):/.match(s).captures # => ["2012-01-28 00:00:00", "2012-02-27 23:59:59"]
dt1 # => "2012-01-28 00:00:00"
dt2 # => "2012-02-27 23:59:59"
这是使用“句点”和“to”以及尾随的“:”来标记要搜索的范围的开始和结束,并在每个日期时间戳中抓取表示日期和时间的非空白字符.
或者,使用“命名捕获”预定义变量:
/period (?<dt1>\S+ \S+) to (?<dt2>\S+ \S+):/ =~ s # => 16
dt1 # => "2012-01-28 00:00:00"
dt2 # => "2012-02-27 23:59:59"
从那时起,如果您想分解返回的值,可以将它们解析为日期:
require 'date'
d1 = DateTime.strptime(dt1, '%Y-%m-%d %H:%M:%S') # => #<DateTime: 2012-01-28T00:00:00+00:00 ((2455955j,0s,0n),+0s,2299161j)>
d1.month # => 1
d1.day # => 28
或者您甚至可以使用子捕获:
matches = /period (?<dt1>(?<date1>\S+) (?<time1>\S+)) to (?<dt2>(?<date2>\S+) (?<time2>\S+)):/.match(s)
matches # => #<MatchData "period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:" dt1:"2012-01-28 00:00:00" date1:"2012-01-28" time1:"00:00:00" dt2:"2012-02-27 23:59:59" date2:"2012-02-27" time2:"23:59:59">
matches['dt1'] # => "2012-01-28 00:00:00"
matches['date1'] # => "2012-01-28"
matches['time2'] # => "23:59:59"
这一切都记录在the Regexp documentation中。