Regular expression for validating year starting from 2020
I am writing a regular expression to validate year starting from 2020.
The below is the regular expression I wrote,
^(20-99)(20-99)$开发者_StackOverflow中文版
It doesn't seem to work. Can anyone point out where did I get it wrong?
Regular expressions don't take ranges like that. You'll want to do something like:
if( year >= 2020 )
presto
I'm being flippant because you're trying to use a regular expression where you can just use a straight-forward comparison. If you have a string, convert the string into an integer first (if you even need to do that with Python). Otherwise, you're going to have some really ugly regular expression that's hard to maintain.
Edit: If you're really keen on using a regular expression (or three), your problem can be broken up into three regular expressions: ^20[2-9]\d$
, ^2[1-9]\d\d$
, ^[3-9]\d{3}$
for four-character years. You could combine these into ^(20[2-9]\d|2[1-9]\d\d|[3-9]\d{3})$
.
But note that the regular expression is a) ugly as hell, and b) only accepts years up to 9999. You can mitigate this with judicious use of the +
, so something like:
^(20[2-9]\d+|2[1-9]\d{2,}|[3-9]\d{3,})$
...could work.
But I hope you'll find that just doing year >= 2020
is a lot better.
Edit 2: Hell, that regex is wrong for years greater than 9999. You'll probably want to use:
^(20[2-9]\d|2[1-9]\d{2}|[3-9]\d{3}|[1-9]\d{4,})$
And that still doesn't work if you enter a year like 03852
.
Not certain about python but w.r.t. to regex it doesn't work like you are thinking...ranges are for a single character. So if for some reason you must have a regexp (ie: some sort of regexp data-filled validation engine):
^20[2-9][0-9]|[2-9][1-9][0-9][0-9]$
Any number from 2020-2099 or 2100-9999.
Here is a significantly shorter regex that does what you want:
^(?![01]|20[01])\d{4}$
Validation:
>>> regex = re.compile(r'^(?![01]|20[01])\d{4}$')
>>> all(regex.match(str(x)) if x >= 2020 else not regex.match(str(x)) for x in xrange(10000))
True
If you want from 2023 here is one I done
^20([2-9][3-9]|[3-9][0-9])|2100$
Range is 2023 - 2100
just change the first [3-9] to whatever year you are on. So next year would be [4-9] and so on
^20([2-9][4-9]|[3-9][0-9])|2100$
Range is 2024 - 2100 and so on keep changing the [4-9] for the next year etc..
To expand it even further include Months as YYYY/MM OR YYYY-MM OR YYYY MM
I have this:
^(20([2-9][3-9]|[3-9][0-9])|2100)[\s\/-](0[1-9]|1[0-2])$
精彩评论