简体   繁体   中英

Regex allow only datetime (h:m:s) or an integer

I'm looking for a regex pattern that only accept datetime (eg: 01:02:00) or an integer (123456789), The datetime can accept optional leading zero i mean it can also allow 1:2:10

It should allow or disallow these inputs:

0123456789✅
0123456789 word❌
word❌
01:00:10✅
1:2:10✅
1:10❌
1:2:❌
1:❌

I tried this pattern but not working correctly:

if (preg_match('~^[0-9:]*$|[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}~')) {
    //allowed
}

https://regex101.com/r/mRxBNu/1

I would just use a regex alternation here:

^(?:\d+|\d{1,2}:\d{1,2}:\d{1,2})$

Demo

Explanation of regex:

^                            from the start of the input
(?:
    \d+                      match one or more digits
    |                        OR
    \d{1,2}:\d{1,2}:\d{1,2}  match an H:M:S timestamp
)
$                            end of the input

I'd suggest the following could work:

^\d\d?(?:\d*|:\d\d?:\d\d?)$

See the online demo

  • ^ - Start string anchor.
  • \d\d? - A single digit and an optional one.
  • (?: - Open non-capture group:
    • \d* - 0+ digits;
    • | - Or:
    • :\d\d?:\d\d? - A colon, digit and an optional digit (two times in a row).
    • ) - Close non-capture group.
  • $ - End string anchor.

在此处输入图像描述

This regex will detect any date and a 10 digit Integer/Number

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?: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]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^([0-9]{10})$

Inspired from here:

https://ihateregex.io/expr/date/

I just added the last "|([0-9]{10})" for the 10 digit number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM