4

我的代码:

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”转换为新格式。

4

2 回答 2

2

这是一个快速而肮脏的解决方案。该函数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
于 2012-09-11T17:46:44.163 回答
0

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

于 2012-09-11T15:10:10.013 回答