December 23, 20222 min read

Regex for year

A date is a specific day or time period, often given as a combination of a month, date, and year. In this article let's understand how we can create a regex for year and how regex can be matched for a given year.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Structure of a year

The valid year should have the following criteria and structure-

  • The year should be a 4 digit number
  • Year should be between 1000 and 9999

Regex for checking if year is valid or not

Regular Expression for year-


Test string examples for the above regex-

Input StringMatch Output
12does not match
723212does not match

Here is a detailed explanation of the above regex-


Match a single character present in the list below [1-9]
1-9 matches a single character in the range between 1 (index 49) and 9 (index 57) (case insensitive)
Match a single character present in the list below [0-9]
{3} matches the previous token exactly 3 times
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case insensitive)
Global pattern flags
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
g modifier: global. All matches (don't return after first match)

Hope this article was useful to check if the string is a valid year or not.

Share this blog
Tagged in :
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article
Next Article