¿Cuál es el patrón regex para datetime (2008-09-01 12: 35: 45?


¿Cuál es el patrón de expresiones regulares para DateTime (2008-09-01 12:35:45 ) ?

Recibo este error:

No se ha encontrado un delimitador final ' ^ '

Usando:

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');

Da este error:

Advertencia: preg_match () [función.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php en línea 19

Author: abatishchev, 2008-09-01

11 answers

@Espo: Solo tengo que decir que la expresión regular es increíble. Odiaría tener que escribir el código que hizo algo útil con las coincidencias, como si realmente quisiera averiguar qué fecha y hora escribió el usuario.

Parece que la solución de Tom sería más sostenible, ya que es un millón de veces más simple y con la adición de algunos paréntesis puede obtener fácilmente los valores que el usuario escribió:

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

Si está utilizando perl, entonces puede obtener los valores con algo así:

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

Otros idiomas tendrán una capacidad similar. Tenga en cuenta que tendrá que hacer algunos mods menores a la expresión regular si desea aceptar valores como meses de un solo dígito.

 47
Author: Greg Hewgill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-01 11:23:07

Una versión simple que funcionará para el formato mencionado, pero no para todos los demás según @Espos:

(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) 
 22
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-01 11:14:40

Http://regexlib.com/REDetails.aspx?regexp_id=610

^(?= \ d) (?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?: \x20/$))|(?: 2 [0-8]|1\d / 0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d \ d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$


Este RE valida ambas fechas y/o patrones de tiempos. Días en febrero. también validado para años bisiestos. Fechas: en formato dd/mm/aaaa o d/m/aaaa entre 1/1/1600 - 31/12/9999. Ceros principales son opcionales. Los separadores de fecha pueden ser cualquiera de los guiones coincidentes ( -), barras(/) o períodos(.) Tiempos: en el hh: MM: ss AM / PM formato de 12 horas (12: 00 AM - 11:59: 59 PM) o hh: MM: ss tiempo militar formato (00:00:00 - 23:59:59). Los 12 hora formato: 1) puede tener un liderando cero por la hora. 2) Minutos y los segundos son opcionales para el 12 formato de hora 3) AM o PM se requiere y distingue entre mayúsculas y minúsculas. Militar 1) debe tener un cero inicial para todas las horas menos de 10. 2) Los minutos son manditory. 3) los segundos son opcionales. Datetimes: combinación de los anteriores formato. Una cita primero y luego una hora separados por un espacio. ex) dd / mm / aaaa hh: MM: ss


Editar : Asegúrese de copiar la expresión regular de la regexlib.com sitio web como StackOverflow a veces elimina / destruye caracteres especiales.

 7
Author: Espo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-01 11:22:41
^([2][0]\d{2}\/([0]\d|[1][0-2])\/([0-2]\d|[3][0-1]))$|^([2][0]\d{2}\/([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$
 3
Author: Javad Yousefi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-03 11:27:34
$date = "2014-04-01 12:00:00";

preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date, $matches);

print_r($matches);

Matches las coincidencias serán:

Array ( 
   [0] => 2014-04-01 12:00:00 
   [1] => 2014 
   [2] => 04 
   [3] => 01 
   [4] => 12 
   [5] => 00 
   [6] => 00
)

Una manera fácil de romper una cadena formateada datetime.

 3
Author: Philip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-01 23:11:26

Con respecto a la respuesta de Imran del 1 de septiembre de 2008 a las 12:33 falta una : en el patrón los patrones correctos son

preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m1);
print_r( $m1 );
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m2);
print_r( $m2 );
preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45', $m3);
print_r( $m3 );

Esto devuelve

Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 ) 
 0
Author: deni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-18 18:19:36

Aquí está mi solución:

/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\:([012345][0-9])\:([012345][0-9])$/u
 0
Author: KoKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-30 13:45:03

He modificado el patrón de regex de http://regexlib.com/REDetails.aspx?regexp_id=610 . El siguiente patrón debe coincidir con su caso.

^(?=\d)(?:(?:1[6-9]|[2-9]\d)?\d\d([-.\/])(?:1[012]|0?[1-9])\1(?:31(?<!.(?:0[2469]|11))|(?:30|29)(?<!.02)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$

AAAA-MM-DD HH:MM: SS

 0
Author: themepark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 00:15:35

PHP preg functions necesita que su expresión regular esté envuelta con un carácter delimitador, que puede ser cualquier carácter. No puede usar este carácter delimitador sin escapar dentro de la expresión regular. Esto debería funcionar (aquí el carácter delimitador es/):

preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

// or this, to allow matching 0:00:00 time too.
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45');

Si necesita emparejar líneas que solo contengan datetime, agregue ^ y ^ al principio y al final de la expresión regular.

preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45');

Enlace al manual de PHP preg_match()

 -1
Author: Imran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-11 04:38:06

Aquí hay una versión simplificada (originada de la respuesta de Espo). Comprueba la exactitud de la fecha (incluso año bisiesto), y hh: mm: ss es opcional
Ejemplos que funcionan:
- 31/12/2003 11:59:59
- 29-2-2004

^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))(|([01]\d|2[0-3])(:[0-5]\d){1,2})?$
 -1
Author: Duc Tran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-11 03:36:59

Aquí está mi solución:

[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\d

Demo de depuración

Https://regex101.com/r/lbthaT/4

 -1
Author: Yeongjun Kim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-05 12:58:49