Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

php - 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]|1d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])2(?<year>(1[6-9]|[2-9]d)d{2})(?:(?=x20d)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:wwwindex.php on line 19

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...