in reply to Re: simple pattern match ?
in thread simple pattern match ?

To match a digit between 0 and 59, or a *, you could use the following regular expression:
([012345]?\d)
Actually, that would fail on single digit entries between 0 and 5 - because the first (optional) part of the expression would match, and then there would be no 2nd digit to match the second (required) part (\d). For the sake of the exercise, I had a play around with it and the following seems to work (for 0-59):
/^(?:[0-9*]|[12345]\d)$/
(But I also echo your sentiments about not re-inventing the wheel)

Cheers,
Darren :)

Replies are listed 'Best First'.
Re^3: simple pattern match ?
by johngg (Canon) on Mar 15, 2006 at 19:07 UTC
    This is a quick, nasty way of matching a range without spending a lot of effort on crafting a clever regular expression.

    @range = (0 .. 59); { local $" = '|'; $rxMatchIt = qr{(@range)}; }

    You end up with a regular expression which says match 0 or 1 or ... 59. This falls over if there are leading zeros but could easily be adapted to cope. I like nifty regular expressions but sometimes quick and dirty gets the job done.

    Cheers,

    JohnGG

Re^3: simple pattern match ?
by Corion (Patriarch) on Mar 15, 2006 at 16:50 UTC

    On Perl 5.8.5, the pattern works for me:

    #!perl -w for (qw( 00 01 02 03 04 05 06 07 08 09 0 1 2 3 4 5 6 7 8 9 10 20 30 40 50 58 59 )) { die "Ooops: $_ didn't match the regular expression" unless /([012345]?\d)/; }; print "All numbers passed.";
      So it does :)

      So my logic above is flawed. I'm almost certain that I tested your pattern earlier and it failed - but obviously not.

      Anyway, I guess that means that the regex engine is "smart enough" to know that even if it gets a match with the [012345]? - it has to "release" it to the \d if there is no 2nd digit - yes?

        Yes. The regex engine uses backtracking and marks its location whenever it has to make a decision. If the first decision doesn't work out, it backtracks to the last marked point and uses the next possible decision. The ? regex operator is such a decision point and I guess that basically, the two possibilities for a match are:

        [012345]\d
        and

        \d
        So in this case, it would not get a match when trying /[012345]\d/ against 5, so it backtracks, and tries /\d/, which works.