我有话要说
line = "start running at Sat April 1 07:30:37 2017"
我想提取
"Sat April 1 07:30:37 2017"
我试过了...
line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
line.split("start running at ").last
end
...但是还有其他方法吗?
最佳答案
这是一种从任意字符串中提取代表给定格式时间的子字符串的方法。我假设字符串中至多有一个这样的子字符串。
require 'time'
R = /
(?:#{Date::ABBR_DAYNAMES.join('|')})\s
# match day name abbreviation in non-capture group. space
(?:#{Date::MONTHNAMES[1,12].join('|')})\s
# match month name in non-capture group, space
\d{1,2}\s # match one or two digits, space
\d{2}: # match two digits, colon
\d{2}: # match two digits, colon
\d{2}\s # match two digits, space
\d{4} # match 4 digits
(?!\d) # do not match digit (negative lookahead)
/x # free-spacing regex def mode
# /
# (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s
# (?:January|February|March|...|November|December)\s
# \d{1,2}\s
# \d{2}:
# \d{2}:
# \d{2}\s
# \d{4}
# (?!\d)
# /x
def extract_time(str)
s = str[R]
return nil if s.nil?
(DateTime.strptime(s, "%a %B %e %H:%M:%S %Y") rescue nil) ? s : nil
end
str = "start eating breakfast at Sat April 1 07:30:37 2017"
extract_time(str)
#=> "Sat April 1 07:30:37 2017"
str = "go back to sleep at Cat April 1 07:30:37 2017"
extract_time(str)
#=> nil
或者,如果与 R
匹配,但是 Time#strptime引发异常(意味着 s
不是给定时间格式的有效时间)可以引发异常以建议用户。
关于ruby - 如何提取 ruby 中的一部分线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158166/