Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Checking number in file name

by space_monk (Chaplain)
on May 19, 2013 at 15:07 UTC ( #1034223=note: print w/replies, xml ) Need Help??

in reply to Checking number in file name

Whilst (\w+) will match on digits also, you're probably better using ^(\d+); you're also better putting the start marker outside the brackets. Note also that "\w" also accepts "_" characters, so if you know a filename is going to be a certain pattern you are best tying it down as tightly as possible.

Note that also you probably need to look at greedy and non-greedy matching - that initial (\w+) may be getting all the characters

I admit regexs still manage to beat me occasionally and one way of building up patterns is to start at the simplest and incrementally make it more complex.

1) $filename =~ /^(\d+)_/ 2) $filename =~ /^(\d+)_(\d+)/ 3) $filename =~ /^(\d+)_(\d+)_(\w+)/ ....

You can also use glob to find all files that match a certain pattern.

If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

Replies are listed 'Best First'.
Re^2: Checking number in file name
by Anonymous Monk on May 19, 2013 at 15:38 UTC
    The file name could start with some letters as well, here is what I am thinking that could work, since I know that a true file name needs to be at least 7 chars long:
    #!/usr/bin/perl use strict; use warnings; my @files = qw( 000231263444_01_XY_20130110_061717.txt 17034513_01_WQ_ +20130511_053551.txt 12345670_01_XY_20130110_061717.txt BOA034513_01_W +Q_20130511_053551.txt); foreach my $file(@files) { $file =~/(^\w+)_(\w{1,2})_(\w{1,2})_(\w+)_(\w+)\.txt$/i; #my $accountnumber = $1; # test my $accountnumber = "BOA034513"; if( ($file=~/$accountnumber/gi) && ($accountnumber=~/\w{7,}/g) ) { print "\n Found - *$accountnumber* - *$file*\n"; }else{ print "\n Not Found - *$accountnumber* - *$file*\n"; } }
    Any example of how the same process could be done using "GLOB"?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1034223]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2017-05-28 14:40 GMT
Find Nodes?
    Voting Booth?