Given a value I want to validate it to check if it is a valid year. My criteria is simple where the value should be an integer with 4
characters. I know this is not the best solution as it will not allow years before 1000
and will allow years such as 5000
. This criteria is adequate for my current scenario.
What I came up with is
\d{4}$
While this works it also allows negative values.
How do I ensure that only positive integers are allowed?
No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. In above example '?' indicates that the two digits preceding it are optional. They may not occur or occur at the most once.
Years from 1000 to 2999
^[12][0-9]{3}$
For 1900-2099
^(19|20)\d{2}$
You need to add a start anchor ^
as:
^\d{4}$
Your regex \d{4}$
will match strings that end with 4 digits. So input like -1234
will be accepted.
By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.
The "accepted" answer to this question is both incorrect and myopic.
It is incorrect in that it will match strings like 0001
, which is not a valid year.
It is myopic in that it will not match any values above 9999. Have we already forgotten the lessons of Y2K? Instead, use the regular expression:
^[1-9]\d{3,}$
If you need to match years in the past, in addition to years in the future, you could use this regular expression to match any positive integer:
^[1-9]\d*$
Even if you don't expect dates from the past, you may want to use this regular expression anyway, just in case someone invents a time machine and wants to take your software back with them.
Note: This regular expression will match all years, including those before the year 1, since they are typically represented with a BC designation instead of a negative integer. Of course, this convention could change over the next few millennia, so your best option is to match any integer—positive or negative—with the following regular expression:
^-?[1-9]\d*$
This works for 1900 to 2099:
/(?:(?:19|20)[0-9]{2})/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With