Parsing dates with regex in C#
I'm working on a C#开发者_开发问答 app, and I get a string with a date or part of a date and I need to get the day, month and year for that string. For example:
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"
Any idea?
Don't use regular expressions for that. Instead use
DateTime temp = DateTime.Parse(example);
Now a lot of useful properties are at your disposal. temp.Day
e.g.
DateTime.ParseExact()
allows you to define the custom format of the string you want to parse and then you have a nice DateTime
object to use.
But if you say that you can have strange formats like "year hour:minute", I think you can go with a 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;
For the string "2010 12:44", you can use the pattern @"^(?<year>\d\d\d\d) (?<hour>\d\d?):(?<minute>\d\d?)$"
For the string "12-2010", you can use the pattern @"^(?<month>\d\d?)-(?<year>\d\d\d\d)$"
精彩评论