Issue
I'm trying to write some javascript regex to validate the monthly portion of a cron job is valid. (For those who aren't familiar, check out https://crontab.guru)
The cron job monthly portion can specify a job that is bi-monthly, every 3 months, 4 months, or 6 months.
A job that occurs every 4 months could be specified with these 4 formats:
- * * * */4 *
- * * * 04,08,12 *
- * * * 4,8,12
- * * * 04,8,12
- * * * 4,08,12
The regex for the first format could look like: ([*][/][2346])
which can be boolean ORed with the regex to cover the rest.
For the rest, I came up with (0?[1-9]|1[012])(,(0?[1-9]|1[012]))*
for a complete regex of: (0?[1-9]|1[012])(,(0?[1-9]|1[012]))*|([*][/][2346])
but this doesn't seem to work!
Using the regex tester at https://regexr.com/4jp54, one can see that each regex to the right of the first and second boolean OR (|
) doesn't work as expected such that the two instances |1[012]
don't seem to work.
So 01,03,5,7,09
would get matched, but 01,03,5,7,09,11
and 4,8,12
would not as the 11
and 12
in each respective expression doesn't get matched.
Does anyone know what I'm doing wrong?
Solution
If you want to support every 2, 3, 4, 6 month as stated, including single month such as * * * 3 *
, and odd month such as * * * 3,7,11 *
you can use this regex (regex is for month portion only) :
/^(\*\/[2346]|(0?[1-9]|1[012])(,(0?[1-9]|1[012])){0,5})$/
Explanation:
^
- anchor at start(
- group start\*\/[2346]
- fraction format, such as/4
|
- OR(0?[1-9]|1[012])
- month number1
...12
, optional leading zero(,(0?[1-9]|1[012])){0,5}
- pattern repeated 0 to 5 times of:,
followed by month number
)
- group end$
- anchor at end
This will validate months such as:
*/2
*/4
06 // 1x - once a year
02,10 // 2x - every 6 month
03,07,11 // 3x - every 4 odd month
4,8,12 // 3x - every 4 even month
03,6,9,12 // 4x - every 3 month
02,4,6,8,10,12 // 6x - every 2 month
Answered By - Peter Thoeny Answer Checked By - Willingham (WPSolving Volunteer)