DebugPointer
Published on

Regex for year

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-

/^[1-9][0-9]{3}?)$/gm

Test string examples for the above regex-

Input StringMatch Output
12does not match
723212does not match
1999matches
9999matches
6378matches

Here is a detailed explanation of the above regex-

/^[1-9][0-9]{3}?)$/gm

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.