[regex] Regular Expression Match to test for a valid year

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?

This question is related to regex string validation string-matching

The answer is


In my case I wanted to match a string which ends with a year (4 digits) like this for example:

Oct 2020
Nov 2020
Dec 2020
Jan 2021

It'll return true with this one:

var sheetName = 'Jan 2021';
var yearRegex = new RegExp("\b\d{4}$");
var isMonthSheet = yearRegex.test(sheetName);
Logger.log('isMonthSheet = ' + isMonthSheet);

The code above is used in Apps Script.

Here's the link to test the Regex above: https://regex101.com/r/SzYQLN/1


If you need to match YYYY or YYYYMMDD you can use:

^((?:(?:(?:(?:(?:[1-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:[2468][048]|[13579][26])00))(?:0?2(?:29)))|(?:(?:[1-9]\d{3})(?:(?:(?:0?[13578]|1[02])(?:31))|(?:(?:0?[13-9]|1[0-2])(?:29|30))|(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8])))))|(?:19|20)\d{2})$

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...


/^\d{4}$/ This will check if a string consists of only 4 numbers. In this scenario, to input a year 989, you can give 0989 instead.


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*$

Use;

^(19|[2-9][0-9])\d{2}$ 

for years 1900 - 9999.

No need to worry for 9999 and onwards - A.I. will be doing all programming by then !!! Hehehehe

You can test your regex at https://regex101.com/

Also more info about non-capturing groups ( mentioned in one the comments above ) here http://www.manifold.net/doc/radian/why_do_non-capture_groups_exist_.htm


You can also use this one.

([0-2][0-9]|3[0-1])\/([0-1][0-2])\/(19[789]\d|20[01]\d)

This works for 1900 to 2099:

/(?:(?:19|20)[0-9]{2})/

To test a year in a string which contains other words along with the year you can use the following regex: \b\d{4}\b


Building on @r92 answer, for years 1970-2019:

(19[789]\d|20[01]\d)

You could convert your integer into a string. As the minus sign will not match the digits, you will have no negative years.


In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.

Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.

This will work for exact matching using non-capturing groups:

(?:19|20)\d{2}


I use this regex in Java ^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|[2-9][0-9])[0-9]{2}$

Works from 1900 to 9999


Years from 1000 to 2999

^[12][0-9]{3}$

For 1900-2099

^(19|20)\d{2}$

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to string-matching

Filter multiple values on a string column in dplyr PowerShell and the -contains operator Check if string matches pattern How to check if matching text is found in a string in Lua? Check whether a string contains a substring Perl - If string contains text? How to search a specific value in all tables (PostgreSQL)? javascript regular expression to check for IP addresses Regular Expression Match to test for a valid year How do I check if a string contains a specific word?