user180574
user180574

Reputation: 6094

Does Ruby's regular expression comply with standard?

I need to match the following string, basically for crontab.

0 2 * * 0,1,2,3,4,5,6

which is "0 2 * *" followed by at most 7 numbers from 0 to 6 (i.e., seven days of week) separated by comma. Below is what I got from ruby.

$ irb
irb> /0 2 \* \* [0-6]((,[0-6]){0,6})/ =~ "0 2 * * 1,2"
=> 0
irb> /0 2 \* \* [0-6]((,[0-6]){0,6})/ =~ "0 2 * * 7"
=> nil
irb> /0 2 \* \* [0-6]((,[0-6]){0,6})/ =~ "0 2 * * 0,1,2,3,4,5,6,7"
=> 0

For the last one, why it still matches?

Then I test the same regular expression using http://regexpal.com/. It works as expected, which indicates my regular expression is correct.

Upvotes: 1

Views: 138

Answers (1)

Wayne Conrad
Wayne Conrad

Reputation: 108259

Because your regular expression is not anchored, it will match any string that contains it, even if the string has extra characters before or after the pattern.

Change this:

/0 2 \* \* [0-6]((,[0-6]){0,6})/

to this:

/^0 2 \* \* [0-6]((,[0-6]){0,6})$/

And it will work as you expect. ^ anchors to the beginning of a line; $ to the end.

When you try the last regex and string on http://regexpal.com, you may notice that the portion of the string that matches is highlighted:

0 2 * * 0,1,2,3,4,5,6,7

Only the portion that is highlighted matched. This shows you that regexpal and Ruby are doing the same thing, in this case.

Upvotes: 2

Related Questions