I am really stuck at a place where I want a regex for a cron Expression where the scenario is the length of cron Expression should be equal to 5.
Also it should accept every possible cron expression but it should be equal to 5.
For Example :-
- 0 0 12 * * ? -> this is invalid as this expression is not equalTo 5
- 0 0 12 * * -> this is valid cron
similarly,
-
-
-
-
-
- -> this is valid cron expression as it is == 5
-
-
-
-
-
-
-
-
-
-
- -> this is invalid as it is !== 5
-
-
-
-
-
0 15 10 * * ? 2005 -> this also invalid cron
0 15 10 * 2005 -> this is valid cron
0 0-5 14 -> Invalid
0 0-5 14 * * -> Valid
This are scenarios where the cron expression should be === 5 if it is less than 5 or greater than 5 then it should give error as (CronExpression is invalid)
Any way we can only do this through regex or can write a javascript function which will handle such case for cronExpression ?
I have search everywhere for this regex but couldn't found any regex with such scenario
Any help with example will be appreciated!!!
Thanks in advance!
CodePudding user response:
I don't think you need a regexp:
You could do:
function validateCron(cron){
return cron.split(' ').length === 5;
}
CodePudding user response:
your question need some decent clarification.
Let's assume you need to check whether your expression contains exactly 5 parts. Then you can check it just by splitting, just like Roberto Falcon wrote. Note that some expressions allow using any type of whitespace, not just basic space.
What is exact specification of that expression? Do you need to use it with Linux cron, Oracle CronTrigger, java org.quartz.CronExpression or something else? There are minor differences in allowed characters.
Do you need to check it youself? The are possibilities like https://www.npmjs.com/package/cron-parser - just try-catch parser.parseExpression(). You should check your exact specification - it does not allow some special characters.
Finally, if you need to regexp validate by yourself, I would recommend to split it and validate each part separately. Putting all in one regexp would result in huge and hard to read text blob.