0

Tried to create a (simplified) regex for cron patterns for myself and came up with the following one:

^(((\d+(,\d+)*)|(\d+-\d+)|(\*(\/\d+)?))(\s+(\d+(,\d+)*)|(\d+-\d+)|(\*(\/\d+)?)){4})$ 

This is generated by

var variant1 = "\\d+(,\\d+)*"; var variant2 = "\\d+-\\d+"; var variant3 = "\\*(\\/\\d+)?"; var variants = "(" + variant1 + ")|(" + variant2 + ")|(" + variant3 + ")"; var regex_cron = "^((" + variants + ")(\\s+" + variants + "){4})$"; 

For a lot of cron patterns this is working just fine:

* 4 45 6 7 5 4 45 6 7 */5 3,4 45,6,8 6 5 

But if I use an asterisk in "group" 2 or higher, it fails:

4 * * * * 

I know that there are a couple of regular expressions for recognizing cron patterns available on the internet, but I really would like to know where I went wrong during creating the regex.

1 Answer 1

0

The probleme in your regex lies in the grouping of the second part:

var regex_cron = "^((" + variants + ")(\\s+" + variants + "){4})$"; --- 

should be :

var regex_cron = "^((" + variants + ")(\\s+(" + variants + ")){4})$"; ! ! 

Because as you wrote it the \s+ (---) belongs only to the first part of the OR and the 2 next one don't match because there is a space.

May be it would be better practice to group the variants var together:

var variants = "((" + variant1 + ")|(" + variant2 + ")|(" + variant3 + "))"; 

There is a good place to test your regexp: http://www.regexr.com/

And this regexp could be simplified, and in the current state it doesn't match the string that will be the cron command, that should come before the $ matching the end of the line.

1
  • You're right and it's kind of obvious once someone spells it out for me. Thx. Actually I don't check entries of the crontab file but patterns for cron4j (which can be entered by the user and therefore have to be checked). Commented Dec 25, 2014 at 11:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.