Plankton has asked for the wisdom of the Perl Monks concerning the following question:

I know there is a better way to write this ...
return if ! ( /\.[jJ][pP][gG]$/ or /\.[jJ][pP][eE][gG]$/ );
... I thought I could of just done this ...
return if ! ( /\.[jJ][pP][eE][gG]$/ );
... since the [eE] means find zero or more e's or E's right?

Replies are listed 'Best First'.
Re: help with []'s in regex please
by CountZero (Bishop) on Aug 27, 2005 at 20:47 UTC
    /\.jpe?g$/i

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: help with []'s in regex please
by Zaxo (Archbishop) on Aug 27, 2005 at 20:49 UTC
    ... since the [eE] means find zero or more e's or E's right?

    No, it means one upper- or lower-case 'e'. Brackets mean a character class. You can make it accept zero with a question mark.

    The simpler way to write that is with the /i modifier for a case-insensitive match:     return if ! /\.jpe?g$/i; I've made the 'e' optional in the match.

    After Compline,
    Zaxo

      But that wouldn't find .jpeg

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

        Golly, you're quick! It didn't take me a minute from posting to fix that ;-)

        After Compline,
        Zaxo

Re: help with []'s in regex please
by Tanktalus (Canon) on Aug 27, 2005 at 20:47 UTC
    return if ! ( /\.[jJ][pP][eE]?[gG]$/ );

    The brackets mean "one of these characters" while the question mark means "the preceeding element is optional" or "0 or 1 of the preceeding element", depending on how you want to look at it.

    Of course, I'd switch out the "if !" for "unless"... but there be another religious war ;-)

    (PS - unless performance matters, just use the i modifier - /\.jpe?g/i is just about as fast as the above.)

Re: help with []'s in regex please
by Anonymous Monk on Aug 27, 2005 at 20:53 UTC
    since the [eE] means find zero or more e's or E's right?

    Actually not quite. [Ee] means find exactly one e or E. [Ee]* means find zero or more, whereas [Ee]? means find either zero or one.

    By the way, another trick you may find useful is case-insensitive matching. So actually you can just say:

    return if ! (/\.jpe?g$/i );

    Take a look at perlretut and Common Regex Gotchas.