RegEx for dates

RegEx for dates

11
Basic UserBasic User
11

    17:05 - Jan 29#1

    I am trying to write a regular expression to find dates with the format YYYY-MM-DD HH:MM:ss. I tried the following expression, but UE returns You have entered an invalid regular expression. I tried both Unix and Perl options with the same result. 

    What am I missing?

    Code: Select all

    qr/^(?:[1-9]\d{3}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d{0}[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29[[:space:]]([01]?\d|2[0-3]):([0-5]\d):([0-5]\d)$
    Thank you!

    6,612548
    Grand MasterGrand Master
    6,612548

      17:38 - Jan 29#2

      This should be a Perl regular expression. qr/ at the beginning is interpreted as literal string.

      The regular expression is invalid because of one ) too much within: (?:0[48]|[2468][048]|[13579][26])00)-02-29
      One of the two closing round brackets must be removed or an opening round bracket is missing somewhere.

      You know that ^ means beginning of a line and $ means end of the line.

      Is it really necessary that the search expression finds only valid dates/times and ignores an invalid date like 2023-02-30 or an invalid time like 14:61:40?

      [12][0-9]{3}-[01][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9] would be much easier as also (?:19|20)[0-9]{2}-[01][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]. Both could match also invalid dates/times and ignore valid times with leap second 60. But it should be enough if the goal is finding dates in the format yyyy-MM-dd HH:mm:ss.
      Best regards from an UC/UE/UES for Windows user from Austria

      11
      Basic UserBasic User
      11

        18:01 - Jan 29#3

        Thank you so much!

        18572
        MasterMaster
        18572

          23:26 - Jan 29#4

          Just a little note - I suggest to use backreferences for reused matches like date/time field separators in your case. It is more convenient and safer.

          E.g. Mofi's regexp
          [12][0-9]{3}-[01][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]

          and the modified version
          [12][0-9]{3}(-)[01][0-9]\1[0-3][0-9] [0-2][0-9](:)[0-5][0-9]\2[0-5][0-9]

          or more generic version (just for demonstration because some separators are usually used in a different field order)
          [12][0-9]{3}([-/.])[01][0-9]\1[0-3][0-9] [0-2][0-9]([:.,])[0-5][0-9]\2[0-5][0-9]

          BR, Fleggy