简体   繁体   中英

Making regex for preg_match greedy to only accept certain values?

I have a CSV file that has a entry of strings that represents time/dates as follows :

20190816T16:10:10

I have created the following regex to preg_match but want to have the hour/mins and seconds to only allow certain numbers (eg hours would be 24 hour clock so only accept 00-23, while minutes & seconds would only accept 00-59)

/\\d{8}[AZ]\\d{2}:\\d{2}:\\d{2}/

Can anyone suggest how to change this to ensure this regex matches the structure I am trying to achieve?

You need to modify your pattern to match the underlying strings making up those ranges:

/\d{8}[A-Z](?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/

Demo

此正则表达式应符合您的结构:

\d{8}[A-Z]([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

You can use ranges (ex: [0-9] ), with a non-capturing group for the hours (minutes & seconds are easy to match):

//            00 to 23       00 to 59
/\d{8}[A-Z](?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d/

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