2015-10-04 45 views
2

我收到了一串字符串,告訴我有關事件,我需要將所有字符串轉換爲開始DateTime和結束DateTime。起初,我嘗試通過字符串逐個字符,但當字符串中有多個日期時,它變得太複雜了。我也嘗試過分析許多日期格式,但是當日期和月份先來時,那麼時間,它不起作用。我正在使用C#,並且也嘗試使用正則表達式搜索字符串,但是我遇到了麻煩,因爲我無法將日期匹配到正確的時間。如何獲取隨機字符串中的日期時間?

這裏是我給出的字符串的幾個例子:

九月12-13,2015,週六10:30 a.m.-6p.m.週日上午10時中午

應該有2個日期:

StartDate: 2015/09/12 10:30 EndDate: 2015/09/12 18:00 
StartDate: 2015/09/13 10:00 EndDate: 2015/09/13 12:00 

六月3日至9月9日,2015年,週二,週四下午6-7 ,週日10-11時三十分

多個日期週二/週四/週日的日期範圍:

StartDate: 2015/06/04 18:00 EndDate: 2015/06/04 19:00 
StartDate: 2015/06/07 10:00 EndDate: 2015/06/07 11:00 
StartDate: 2015/06/09 18:00 EndDate: 2015/06/09 19:00 
StartDate: 2015/06/11 18:00 EndDate: 2015/06/11 19:00 

...繼續以下相同的模式

謝謝。

+1

似乎是令牌的工作......第一次嘗試推廣可能的格式轉換成規則。 –

+0

如果其中一個標準日期 - 時間分析模塊適合您,請嘗試。例如,Perl有一些:http://search.cpan.org/~gbarr/TimeDate-2.30/lib/Date/Parse.pm如果不是,另一個選擇是設計一個小的DSL(領域特定語言)日期格式,並使用像ANTLR或Flex/Bison這樣的解析器生成器來生成代碼。 –

+1

當可能的日期格式如此多樣時,可能的日期格式會是什麼?有些字符串以時間開始,以月份結束,等等。 – Scott

回答

1

這裏是一種可能的方法,以這樣的:

1)掃描/樂星 - >掃描基本令牌。

Names: September, Saturday, AM, etc. 
Numbers: 12, 2015, 9, etc. 
Operators serving as Separators: '-', ',', space, etc. 
    '-' acts as a range operator as in FromDate - ToDate. 
    ',' and space separate components of a date 

2)解析 - >從標記中構建一個解析樹。 3)現在,Parse樹表示由' - '分隔的日期時間條目。

At this point, a date in the tree can be partial or complete. 
Introduce separator when it is missing between adjacent dates or times. 
"Sunday 10a.m noon" is missing separator between '10am' and 'noon' 

4)從分析樹中確定完整和部分日期。

For example, "September 9, 2015" is a complete date, while "June 3" 
is incomplete. After extracting at least one complete date, infer 
the missing elements in incomplete dates from surrounding context. 
"June 3" is incomplete because of missing year, so we grab the 
year from the nearest complete date as 2015. 

5)如果一個完整的日期不能在上述步驟中可以發現,

Use two adjacent dates and let them fill in missing parts 
from each other to arrive at a complete one. "September 12 - 13, 2015" 
is one such example. Left side of the separator is missing 
year and can get it from right side. Figure out the date for 
a day of week, like Thursday from the complete date in the string 
+0

只是好奇,你能描述爲這個問題實施的解決方案的高層次設計嗎? –

相關問題