2012-09-11 31 views
2

我的代码:如何扭转Date.parse()

require 'Date' 

s = "I'm going away on Oct 2, 2012th" 
puts Date.parse(s) 

=> 2012-10-02 

我想从我的琴弦删除的日期,我发现Date.parse(s)。问题是,我知道有一个日期,但不知道它是如何写入字符串的。我知道Date.parse找到它并将“2012-10-02”转换为新格式。

+0

的'parse'方法丢弃除了有效日期的一切。由于您不知道格式或长度,因此您必须测试字符串中每个可能的字符集。不是很漂亮。你想达到什么目的? –

回答

0

这是一个快速和肮脏的解决方案。函数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 
0

Date似乎无法告诉你它在哪里找到日期。您可能不得不编写自己的自定义日期查找器。