jazz250
asked on
finding a match on several regular expressions
i have the following code, it prints "match" if the $filename variable matches the regular expression on $regex
$regex=".*\.mp3";
$filename='test.mp3';
if ($filename =~ m/$regex/)
{
print 'match';
}
else
{
print 'not match';
}
I need to compare not just 1 but many regular expressions... I need to print "match" in case my variable $filename matches any of serveral regular expressions
that i have on a text file
(the name of the file is regex.txt)
regex.txt contains the following data:
.*\.mp3
.*\.jpg
somename
.*\.txt
(\d)
.*\.avi
how can i export all of those regular expressions from my regex.txt file and check them one by one to see if one of them matches my $filename variable??
$regex=".*\.mp3";
$filename='test.mp3';
if ($filename =~ m/$regex/)
{
print 'match';
}
else
{
print 'not match';
}
I need to compare not just 1 but many regular expressions... I need to print "match" in case my variable $filename matches any of serveral regular expressions
that i have on a text file
(the name of the file is regex.txt)
regex.txt contains the following data:
.*\.mp3
.*\.jpg
somename
.*\.txt
(\d)
.*\.avi
how can i export all of those regular expressions from my regex.txt file and check them one by one to see if one of them matches my $filename variable??
Language?
ASKER
Perl
Sorry, i thought i've posted it on the perl section
Sorry, i thought i've posted it on the perl section
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#!/usr/bin/perl
open(IN, "regex.txt") or die "regex.txt $!";
chomp( my @re=<IN>);
close IN;
my $re = join"|",@re;
foreach(qw(test1.mp3 test2.txt test3.jpg1 12345 somename somname) ){
print "$_ matched",/$re/o?"":" nothing","!\n";
}
__END__
see also
perldoc -q "How do I efficiently match many regular expressions at once?"
open(IN, "regex.txt") or die "regex.txt $!";
chomp( my @re=<IN>);
close IN;
my $re = join"|",@re;
foreach(qw(test1.mp3 test2.txt test3.jpg1 12345 somename somname) ){
print "$_ matched",/$re/o?"":" nothing","!\n";
}
__END__
see also
perldoc -q "How do I efficiently match many regular expressions at once?"
ozo, that perldoc actually used the method I was using and doesn't say join "|" @regex would be more efficient than loop. Is there any reason why you were refering to the perldoc?
IMO, in most cases it's better to not use "|" since while it might gains minimal speed and some code clarity, it could lose big if used in unsuitable situations in terms of performance. That's why I did not choose the join "|" one and used loop instead.
IMO, in most cases it's better to not use "|" since while it might gains minimal speed and some code clarity, it could lose big if used in unsuitable situations in terms of performance. That's why I did not choose the join "|" one and used loop instead.