匹配切片的字符串

时间:2019-03-06 12:01:57

标签: ruby string

我正在尝试使用case语句:

week # => "03 – 09 MAR 2019"
first_day = week.slice(0..2) # => 03
last_day = week.slice(5..7) # => 09
month = week.slice(8..11) # => MAR
year = week.slice(12..17) # => 2019
puts month # >> MAR
case month
when 'JAN' then month_num = '01'
when 'FEB' then month_num = '02'
when 'MAR' then month_num = '03'
when 'APR' then month_num = '04'
when 'MAY' then month_num = '05'
when 'JUN' then month_num = '06'
when 'JUL' then month_num = '07'
when 'AGO' then month_num = '08'
when 'SEP' then month_num = '09'
when 'OCT' then month_num = '10'
when 'NOV' then month_num = '11'
when 'DEC' then month_num = '12'
else month_num = 'ERROR'
end
puts month_num # >> ERROR

但是,case语句始终转到else分支。

为什么变量month_num等于字符串"ERROR"而不是"03"

3 个答案:

答案 0 :(得分:3)

您正在使用puts检查所拥有的内容,因此缺少在结果中观察到空格的功能。您实际上有:

week.slice(0..2) # => "03 "
week.slice(5..7) # => "09 "
week.slice(8..11) # => "MAR "
week.slice(12..17) # => "2019"

要观察自己拥有什么,最好使用p而不是puts

您的范围错误。实际上,这里没有理由使用范围。使用第二个参数指定长度要容易得多

week.slice(0, 2) # => "03"
week.slice(5, 2) # => "09"
week.slice(8, 3) # => "MAR"
week.slice(12, 4) # => "2019"

答案 1 :(得分:2)

您的month"MAR "

尝试

month = week.slice(8..10)

从8到10(含)范围内,三个字符是有意义的。其他部分也一样。

答案 2 :(得分:2)

好像您想解析一个包含特定格式数据的字符串。您可以使用regular expression来匹配日期格式,而不是依赖绝对索引,例如:

PATTERN = /
  (?<first_day>\d{2}) # 2-digit first day
  \s*                 # optional whitespace
  [–-]                # delimiter(s)
  \s*
  (?<last_day>\d{2})  # 2-digit last day
  \s*
  (?<month>\w{3})     # 3-letter month name
  \s*
  (?<year>\d{4})      # 4-digit year
/ix

要提取数据:

str = '03 – 09 MAR 2019'
m = str.match(PATTERN)
#=> #<MatchData "03 – 09 MAR 2019" first_day:"03" last_day:"09" month:"MAR" year:"2019">

m[:first_day] #=> "03"
m[:last_day]  #=> "09"
m[:month]     #=> "MAR"
m[:year]      #=> "2019"

结果可以进一步输入Date.strptime

require 'date'

from = m.values_at(:first_day, :month, :year).join(' ') #=> "03 MAR 2019"
to   = m.values_at(:first_day, :month, :year).join(' ') #=> "09 MAR 2019"

Date.strptime(from, '%d %b %Y')  #=> #<Date: 2019-03-03 ...>
Date.strptime(to, '%d %b %Y')    #=> #<Date: 2019-03-09 ...>

或者_strptime,如果您只对原始值感兴趣:

Date._strptime(from, '%d %b %Y')
#=> {:mday=>3, :mon=>3, :year=>2019}