none
Get DatePart from a string RRS feed

  • Question

  • Hi,

    I have a string

    Dec  4 04:03:27 x9730-node1 syslogd 1.4.1: restart.

    I just want to get the datepart from this string Dec  4 04:03:27 . I dont want to use 'substring', split, etc string operations to achieve it.

    The reason is that this datetime location is not static, It may be positioned at the end of the string, or somewhere in the beginning.

    By using any datetime format specifiers, can we get the datepart?

    Like I specify the datetime format as "MMM  d HH:mm:ss"



    Friday, February 22, 2013 8:49 AM

Answers

  • Your best shot is use some kind of an regular expression. The one I can figure now is the one below, but I'm not sure if it works in all your cases it might also match something not supposed to.

    string pattern = @"\b[a-zA-Z]{3}\s{2}\d+\s\d{2}:\d{2}:\d{2}";
    
    //// beginning
    string value = "Dec  4 04:03:27 x9730-node1 syslogd 1.4.1: restart.";
    
    Match match = Regex.Match(value, pattern);
    
    Console.WriteLine(match.Value);
    
    //// end
    value = "x9730-node1 syslogd 1.4.1: restart Jun  5 19:30:23.";
    
    match = Regex.Match(value, pattern);
    
    Console.WriteLine(match.Value);
    
    //// middle
    value = "x9730-node1 syslogd Sep  8 21:06:00 1.4.1: restart.";
    
    match = Regex.Match(value, pattern);
    
    Console.WriteLine(match.Value);



    • Edited by MasaSam Friday, February 22, 2013 10:34 AM
    • Marked as answer by Mike FengModerator Thursday, February 28, 2013 1:58 PM
    Friday, February 22, 2013 9:33 AM