这是一个快速和肮脏的解决方案。函数date_string
仅返回包含parse
找到的日期 的字符串部分。
require 'date'
DATE_ERROR = -1
# If the string doesn't contain a date, it raises an
# exception. This little helper routine catches the
# exception.
def get_date(s)
date = 0
begin
date = Date.parse(s)
rescue
date = DATE_ERROR
end
date
end
# Returns just the part of the string containing the date
def date_string(s)
# First, find the date contained in the string
date = get_date(s)
return "" if date == DATE_ERROR
# Repeatedly chop off characters from the front to find the
# start of the date
first = 1
while date == get_date(s[first..-1])
first += 1
end
# Repeatedly chop off characters from the end to find the
# end of the date
last = s.length - 2
while date == get_date(s[0..last])
last -= 1
end
#Return just the date
s[first - 1..last + 1]
end
puts date_string("I'm going away on Oct 2, 2012th")
puts date_string("I'm going away on 10/2/12 and not coming back")
puts date_string("10 Nov 1999")
puts date_string("I see no date here")
此输出:
Oct 2, 2012
10/2/12
10 Nov 1999
所以,你可以这样做:
s = "I'm going away on Oct 2, 2012th"
datestr = date_string(s)
s.gsub!(datestr, "")
puts s
的'parse'方法丢弃除了有效日期的一切。由于您不知道格式或长度,因此您必须测试字符串中每个可能的字符集。不是很漂亮。你想达到什么目的? –