I am writing a regular expression to validate year starting from 2020.
The below is the regular expression I wrote,
^(20-99)(20-99)$
It doesn’t seem to work. Can anyone point out where did I get it wrong?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Regular expressions don’t take ranges like that. You’ll want to do something like:
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:…could work.
But I hope you’ll find that just doing
year >= 2020is a lot better.Edit 2: Hell, that regex is wrong for years greater than 9999. You’ll probably want to use:
And that still doesn’t work if you enter a year like
03852.