tags:

views:

86

answers:

2

I there I'm working on a C# app, and I get a string with a date or part of a date and i need to take day, month and year for that string

ex: 
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? tks

+3  A: 

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.

Jens
that will not work for me because my string can also be "2010" or "2010 12:44". this will make DateTime.parse(str) throw an exception
DJPB
Then I'd use DateTime.TryParse and iterate through a few expected formats.
John Weldon
@DJPB: Ah, you didn't say so in the question. =) Update the question to include all possible cases, then.
Jens
A: 

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)$"

Paulo Manuel Santos