2010-04-28 34 views
1

我正在研究一個C#應用程序,並且我得到一個包含日期或部分日期的字符串,並且需要獲取該字符串的日期,月份和年份。例如:用C中的正則表達式解析日期#

string example='31-12-2010' 
string day = Regex.Match(example, "REGULAR EXPRESSION FOR DAY").ToString(); 
string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() 
string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() 

day = "31" 
month = "12" 
year = "2010" 

ex2: 
string example='12-2010' 

string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() 
string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() 

month = "12" 
year = "2010" 

有什麼想法嗎?

回答

4

請勿對此使用正則表達式。 而是使用

DateTime temp = DateTime.Parse(example); 

現在很多有用的特性是在您的處置。 temp.Day例如

+0

那將不適合我,因爲我的字符串也可以是「2010」或「2010 12:44」。這將使DateTime.parse(str)拋出一個異常 – DJPB 2010-04-28 15:19:35

+0

然後我會使用DateTime.TryParse並遍歷一些預期的格式。 – 2010-04-28 16:27:00

+0

@DJPB:啊,你在問題中沒有這麼說。 =) 然後更新問題以包含所有可能的情況。 – Jens 2010-04-29 06:12:32

1

DateTime.ParseExact()允許你定義你想要解析的字符串的自定義格式,然後你有一個很好的DateTime對象使用。
但是,如果你說你可以有像「年小時:分鐘」這樣的奇怪格式,我認爲你可以使用RegEx。

string example = "31-12-2010"; 

    Match m = Regex.Match(example, @"^(?<day>\d\d?)-(?<month>\d\d?)-(?<year>\d\d\d\d)$"); 
    string strDay = m.Groups["day"].Value; 
    string strMonth = m.Groups["month"].Value; 
    string strYear = m.Groups["year"].Value; 

對於字符串「2010 12:44」,您可以使用模式@"^(?<year>\d\d\d\d) (?<hour>\d\d?):(?<minute>\d\d?)$"

對於字符串「12-2010」,您可以使用模式@"^(?<month>\d\d?)-(?<year>\d\d\d\d)$"