Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?

I get this error:

No ending delimiter '^' found

Using:

preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(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])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); 

Gives this error:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19

like image 626
Alexander Morland Avatar asked Sep 01 '08 10:09

Alexander Morland


People also ask

How do I find the regex pattern?

If you want to match for the actual '+', '. ' etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern. Example : \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2) * 3*9".

What is regex date format?

The regex matches on a date with the YYYY/MM/DD format and a "Date of birth:" or "Birthday:" prefix (Year min: 1900, Year max: 2020). For example: Date of birth: 1900/12/01. Date of birth: 2019.01.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


2 Answers

@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.

It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:

(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) 

If you're using perl, then you can get the values out with something like this:

$year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; 

Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.

like image 178
Greg Hewgill Avatar answered Sep 19 '22 13:09

Greg Hewgill


A simple version that will work for the format mentioned, but not all the others as per @Espos:

(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})  
like image 42
Tom Avatar answered Sep 20 '22 13:09

Tom