Regex code for month and year(only 2 digits)

61 Views Asked by At

I'm setting up a bot flow in my live chat for my users. To retrieve some of their rental, we need to ask the last 4 digits of their credit card then expiration date.

Since I have an open text field for the user input, I've added a regex code, but I'm stuck on the second part.

The first bot question for the last 4 digits: ^\d{4}$ this is working perfectly.

The second bot question should be the expiration date in this format: MMYY or MM/YY or MM-YY

I've created the first part of the regex code for the MM and limit from 1 to 12: (0[1-9]|1[1,2])

Then I've added the - or /. This is where I'm stuck:

  1. I want to add an option without the - and /
  2. I want to add the year format only YY (not YYYY) and limit it starting from 23 (2023) and going up to 40 (2040).

My current code isn't working:

(0[1-9]|1[1,2])(\/|-|)(0[1-9]|23[4,0]
3

There are 3 best solutions below

3
Gilles Quénot On

For 23 to 40, use:

\b(?:2[3-9]|3[0-9]|40)\b

Online Demo

The regular expression matches as follows:

Node Explanation
\b the boundary anchor between a word char (\w) and something that is not a word char anchor
(?: group, but do not capture:
2 2
[3-9] any character of: '3' to '9'
| OR
3 3
[0-9] any character of: '0' to '9'
| OR
40 '40'
) end of grouping
\b the boundary anchor between a word char (\w) and something that is not a word char anchor

for the delimiter, as Barmar said in comments, you can use:

[/-]?

The regular expression matches as follows:

Node Explanation
[/-]? any character of: '/', '-' (optional (matching the most amount possible))

Finally

use:

\b(?:0[1-9]|1[0-2]){2}[/-]?(?:2[3-9]|3[3-9]|40){2}\b

If you need capture groups, feel free to adapt a bit.

0
Bohemian On

Try this:

^(0[1-9]|1[012])[-/]?(2[3-9]|3\d|40)$

See live demo.

^ and $ (start and end) ensure the whole input is valid.

/ has no special meaning in regex so does not need escaping, so [-/]? matches the separator (if you're using say javascript, you'll need to escape the slash because slash is a delimiter in that language).

0
Reilas On

"... The second bot question should be the expiration date in this format: MMYY or MM/YY or MM-YY

I've created the first part of the regex code for the MM and limit from 1 to 12: (0[1-9]|1[1,2]) ..."

The syntax [1,2] is incorrect, there are no commas, and the range should be [0-2].

"... Then I've added the - or /. This is where I'm stuck:

1. I want to add an option without the - and /
2. I want to add the year format only YY (not YYYY) and limit it starting from 23 (2023) and going up to 40 (2040). ..."

(?:0[1-9]|1[0-2])[/-]?(?:2[3-9]|3\d|40)

Here is the Wikipedia article on regular expressions.