Which regular expression would be most appropriate for validating a Cronjob expression?

Posted on

Question :

I want to learn a little more about regular expressions. I thought of a good exercise that will be validating if a cronjob expression is correct or not.




Anotherdetailisthatexpressionmustcontain5″members” separated by space. These members, as exemplified above, should be as depicted in the image.

The expression can be evaluated as:


For those who do not understand how cronjob works here is a small example:

Performs hourly

0 * * * * comando

Runs from hour to hour, from 1 to 5

0 1-5 * * * comando

According to the image above, how could I create a validation for a cronjob expression?

I just need to validate the content regarding the definition of the time that will be executed, I do not need to validate the command that comes after the expression.

Note : I just need logic to learn regex, so any language is valid for the answer.


Answer :

Boss, simplex , is it like that ???

Well, I do not know if I understood correctly what you’re looking for, but …

<legend>Valida cron:</legend>
<p>* * * * * /sbin/ping -c 1 > /dev/null</p>	
<input id="jota" type="text"/><button type="button" onclick="valida()">Valida</button>
<p id="isvalid"></p>	

	function valida(){
	var filter_cron = /^s*($|#|w+s*=|(*(?:/d+)?|(?:[0-4]?d)(?:-(?:[0-4]?d)(?:/d+)?)?(?:,(?:[0-4]?d)(?:-(?:[0-5]?d)(?:/d+)?)?)*)s+(*(?:/d+)?|(?:[01]?d|2[0-3])(?:-(?:[01]?d|2[0-3])(?:/d+)?)?(?:,(?:[01]?d|2[0-3])(?:-(?:[01]?d|2[0-3])(?:/d+)?)?)*)s+(*(?:/d+)?|(?:0?[1-9]|[12]d|3[01])(?:-(?:0?[1-9]|[12]d|3[01])(?:/d+)?)?(?:,(?:0?[1-9]|[12]d|3[01])(?:-(?:0?[1-9]|[12]d|3[01])(?:/d+)?)?)*)s+(*(?:/d+)?|(?:[1-9]|1[012])(?:-(?:[1-9]|1[012])(?:/d+)?)?(?:,(?:[1-9]|1[012])(?:-(?:[1-9]|1[012])(?:/d+)?)?)*)s+(*(?:/d+)?|(?:[0-6])(?:-(?:[0-6])(?:/d+)?)?(?:,(?:[0-6])(?:-(?:[0-6])(?:/d+)?)?)*)s+|s+)([^s]+)s+(s*.*)$/;
		document.getElementById("isvalid").innerHTML = "Cron inválido";
		document.getElementById("jota").onfocus = function keydown_e(){
	document.getElementById("isvalid").innerHTML = "Tente novamente você consegue ¯_(ツ)_/¯";
		document.getElementById("isvalid").innerHTML = "Válido";}

Reference e Guide

Leave a Reply

Your email address will not be published. Required fields are marked *