PHP regex optional non-matching groups?
I'm trying to make a date regex that allows years from 1900 to 2099, with the 19 or 20 optiona开发者_运维百科l.
I'm almost there, but I can't find a way to allow the 19 or 20 optional part. Here's what I've got:
(?:20)(?:19)?[0-9][0-9]
Testing results:
String preg_match is this ok?
====== ========== ===========
55 yes yes
1955 yes yes
2055 yes yes
201955 yes no
Can someone help out?
This will do it:
^(?:19|20)?\d{2}$
It says:
^ = Start of string
(?:19|20)? = Match 19 or 20 without capturing, zero or one times
\d{2} = 2 decimal digits
$ = End of string
((20)|(19))?
the pipe means "OR" and they are optional because of the question mark
精彩评论