Home > Software design >  Full Regex for selecting Date Time
Full Regex for selecting Date Time

Time:01-11

I want to select all formats for date and time and i need a full regex. currently i am using this regex:

public const string DateTimeRegex = @"\b(?<datetime>"  
        // Date part
        @"(("  
            @"(\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{2}(\d{2})?)"  
            @"|(\d{1,2}\s (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-zA-Z]*,?\s \d{2}\d{2}?)"  
            @"|((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-zA-Z]*\s \d{1,2},?\s \d{2}\d{2}?)"  
            @"|(\d{4}\-\d{1,2}-\d{1,2})"  
        @")"  
        // Optional time part
        @"("  
            @"[T\s]?\d{1,2}:\d{1,2}(:\d{1,2}(\.\d )?)?(([AP]M)|([\ \-][12]?\d:\d{1,2})|Z)?"  
        @")?)"   
    @")\b";

I have a little problem with this regex, it correctly selects all the dates in the following format, but it cannot select the time (only a few are selected)

11/17/2022 11:36 AM 
  1/6/2023  6:19 PM
 11/3/2022 12:06 PM
  Saturday, December 10, 2022  8:07 AM
    Thursday, January 5, 2023  3:27 AM

output:

11/17/2022
1/6/2023
11/3/2022
December 10, 2022
January 5, 2023

so i need to use another regex for selecting time part

public const string DateTimeRegex2 = @"(\d{1,2}:\d{1,2}(:\d{1,2}(\.\d )?)?(([AP]M)|([\ \-][12]?\d:\d{1,2})|Z)?)";

I tried to merge these 2 regex but unfortunately it doesn't work and date and time are not selected correctly.

now i have a date like this:

25-Dec-2022 12:36

and None of the regexes can not select it.

so I want a regex that selects the following formats:

25-Dec-2022
25-Dec-2022 12:36
25-Dec-2022 12:36 PM
11/17/2022
11/17/2022 12:36
11/17/2022 12:36 PM
1/6/2023
1/6/2023 12:36
1/6/2023 12:36 PM
11/3/2022
11/3/2022 12:36
11/3/2022 12:36 PM
December 10, 2022
December 10, 2022 12:36
December 10, 2022 12:36 PM
January 5, 2023
January 5, 2023 12:36
January 5, 2023 12:36 PM

If any other formats are available, I need to identify them

CodePudding user response:

What about the following RegEx?

(?<date>(?:\d{1,2}\/\d{1,2}\/\d{4}|\d{1,2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}|(?:January|February|March|April|May|June|Jule|August|September|October|November|December) \d{1,2}, \d{4}))(?:\s (?<time>\d{1,2}:\d{1,2}(?: (?:AM|PM))?))?

  • Related