Does anyone know of a reg expression for uk date format

后端 未结 7 993
青春惊慌失措
青春惊慌失措 2021-01-18 21:39

Hi does any one know a reg ex for a uk date format e.g. dd/mm/yyyy.

The dd or mm can be 1 character e.g. 1/1/2010 but the year must always be 4 characters.

T

7条回答
  •  不要未来只要你来
    2021-01-18 22:13

    ^\d{1,2}/\d{1,2}/\d{4}$
    

    will match 1/1/2000, 07/05/1999, but also 99/77/8765.

    So if you want to do some rudimentary plausibility checking, you need

    ^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}$
    

    This will still match 31/02/9999, so if you want to catch those, it's getting hairier:

    ^(?:(?:[12][0-9]|0?[1-9])/0?2|(?:30|[12][0-9]|0?[1-9])/(?:0?[469]|11)|(?:3[01]|[12][0-9]|0?[1-9])/(?:0?[13578]|1[02]))/\d{4}$
    

    But this still won't catch leap years. So, modifying a beast of a regex from regexlib.com:

    ^(?:(?:(?:(?:31\/(?:0?[13578]|1[02]))|(?:(?:29|30)\/(?:0?[13-9]|1[0-2])))\/(?:1[6-9]|[2-9]\d)\d{2})|(?:29\/0?2\/(?:(?:(1[6-9]|[2-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:0?[1-9]|1\d|2[0-8])\/(?:(?:0?[1-9])|(?:1[0-2]))\/(?:(?:1[6-9]|[2-9]\d)\d{2}))$
    

    will match

    1/1/2001
    31/5/2010
    29/02/2000
    29/2/2400
    23/5/1671
    01/1/9000
    

    and fail

    31/2/2000
    31/6/1800
    12/12/90
    29/2/2100
    33/3/3333
    

    All in all, regular expressions may be able to match dates; validating them is not their forte, but if they are all you can use, it's certainly possible. But looks horrifying :)

提交回复
热议问题