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

Hi Monks
I have this regular expression:
if($filename=~/(\w+)\.(\w{3})/gi){print "\nThis is a match::$filename\ +n"}else{print "\nNOMatch::$filename\n";}

I need to make sure that the file name has letters or _(underline), but no spaces and followed by a .(dot) and finally the three letters extension, but I can't figure it out the right match to prevent stranger characters entered for the file name, can anyone help on that?
Thanks a lot!

Replies are listed 'Best First'.
Re: Regular Expression Help
by ikegami (Patriarch) on Jan 06, 2006 at 15:43 UTC

    Your missing the anchors, and the /g, the /i and the parens are unnecessary:

    /^\w+\.\w{3}$/

    But that's not perfect because \w allows for digits, so:

    /^[a-zA-Z_]+\.[a-zA-Z_]{3}$/

    To allow filenames with no extention or with extentions short than 3 characters:

    /^[a-zA-Z_]+(?:\.[a-zA-Z_]{0,3})?$/
      One of my problems is not to allow file names without extentions and with no less than 3 characters.
        No problem. Just use the second snippet instead of the third one.
        How do I say match anything but not allow spaces between words? Like:
        if($filename=~/.*!\s[.](?!bat$|exe$).*$/gi){...
        This is not working if I use .*!\s