in reply to Regex for files

If I understand your requirements, you mean:

# Should match:
messages
messages.1
messages.345
# should not match:
messages.txt
messages.
messages123

If that's correct, I'll assume you know how to open a directory and read the files, so then inside that loop, just see if the filename matches the pattern you're looking for. This pattern looks for a filename starting with "messages" followed optionally by a . and any number of digits. The grouping parentheses around the dot and digits ensure that it will have both or neither.

if($filename =~ /^messages(\.\d+)?/ ){ # this one matches }

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.

Replies are listed 'Best First'.
Re^2: Regex for files
by marinersk (Priest) on Apr 23, 2015 at 03:20 UTC

    Interoperability note: Windows inherits from DOS -- filenames that end in dot are indistinguishable from filenames with no ending dot:

    D:\PerlMonks>echo>message. This is a test. D:\PerlMonks>dir Directory of D:\PerlMonks 04/22/2015 11:12 PM <DIR> . 04/22/2015 11:12 PM <DIR> .. 04/22/2015 11:12 PM 17 message D:\PerlMonks>echo>message This is a test. D:\PerlMonks>dir Directory of D:\PerlMonks 04/22/2015 11:12 PM <DIR> . 04/22/2015 11:12 PM <DIR> .. 04/22/2015 11:12 PM 17 message D:\PerlMonks>echo>"message." This is a test. D:\PerlMonks>dir Directory of D:\PerlMonks 04/22/2015 11:12 PM <DIR> . 04/22/2015 11:12 PM <DIR> .. 04/22/2015 11:12 PM 17 message D:\PerlMonks>

    The nit: Under Windows, message.and messageneed to be in the same category.

Re^2: Regex for files
by bmcquill (Initiate) on Apr 23, 2015 at 04:27 UTC
    Hi, Aaron thanks that regex still returns everything. Any other ideas?

      Add a $ to the end of aaron_baugher's expression, like this: /^messages(\.\d*)?$/. Also note the change of the + to a *

        Good catch on the $ anchor; thank you. Re-reading the original post, I see that either he clarified things or I missed the last sentence the first time I read it. In either case, I think this meets his needs as I now understand them:

        #!/usr/bin/env perl use 5.010; use strict; use warnings; while(<DATA>){ chomp; if( /^messages(\.|\.\d)?$/ ){ say "Match: $_"; } else { say "No match $_"; } } __DATA__ messages messages. messages.1 messages.txt messages.12345

        To the original poster: since the regex only allows "messages" to be followed by zero or one groupings of "dot" or "dot digit", extensions like ".txt" will not match, so you don't have to do anything special to eliminate them. I also dropped the + qualifier after the digit since you specified that only a single digit after the dot is acceptable.

        Aaron B.
        Available for small or large Perl jobs and *nix system administration; see my home node.