DebugPointer
Published on

Regex for month

Regex for month

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 month and how regex can be matched for a given month name.

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 month name

The month should have the following criteria and structure-

  • Month can also be a string like January, February, March, April, May, June, July, August, September, October, November, December
  • Month can also be a string like Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

Regex for checking if month name is valid or not

Regular Expression for month name-

/^(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)$/igm

Test string examples for the above regex-

Input StringMatch Output
Janudoes not match
Fedoes not match
Marchmatches
Aprmatches
decembermatches

Here is a detailed explanation of the above regex-

/^((0[13578]|1[02])(\/|-|\.)(0[1-9]|[12][0-9]|3[01])(\/|-|\.)(18|19|20)[0-9]{2})|((0[469]|11)(\/|-|\.)(0[1-9]|[12][0-9]|30)(\/|-|\.)(18|19|20)[0-9]{2})|((02)(\/|-|\.)(0[1-9]|1[0-9]|2[0-8])(\/|-|\.)(18|19|20)[0-9]{2})|((02)(\/|-|\.)29(\/|-|\.)(((18|19|20)(04|08|[2468][048]|[13579][26]))|2000))$/gm

Non-capturing group (?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)
1st Alternative Jan(?:uary)?
2nd Alternative Feb(?:ruary)?
3rd Alternative Mar(?:ch)?
4th Alternative Apr(?:il)?
5th Alternative May
6th Alternative Jun(?:e)?
7th Alternative Jul(?:y)?
8th Alternative Aug(?:ust)?
9th Alternative Sep(?:tember)?
10th Alternative Oct(?:ober)?
11th Alternative (Nov|Dec)(?:ember)?
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)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

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