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 String | Match Output |
---|---|
12 | does not match |
723212 | does not match |
1999 | matches |
9999 | matches |
6378 | matches |
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. In this article, we explored the concept of regular expressions (regex) and their application in validating years. Regex is a versatile tool for searching and manipulating text patterns. By crafting a regex pattern for validating years, we can ensure that a year follows the specified criteria. This skill is valuable for programmers, text editors, and anyone dealing with data manipulation. Understanding the structure of a valid year and crafting an appropriate regex empowers us to efficiently handle year-related data.