All the above are good; just a note for safety's sake, if your use of such a variable as the regular expression ever falls into risk of including metacharacters, you may need to use quotemetato convert it to a regular expression:
#!/usr/bin/perl use strict; my @inputData = ( 'test.dat', 'test.exe', 'testadat.exe', 'testaexe.dat', ); my @regExp = ( 'test.dat', 'test.exe', ); print "----- Without quotemeta ---------------\n"; foreach my $regularExpression (@regExp) { print "Using regular expression /$regularExpression/:\n"; foreach my $inputLine (@inputData) { if ($inputLine =~ /$regularExpression/) { print " Match: \"$inputLine\"\n"; } } } print "----- With quotemeta ------------------\n"; foreach my $regularExpression (@regExp) { my $actualRegularExpression = quotemeta $regularExpression; print "Using regular expression /$actualRegularExpression/:\n"; foreach my $inputLine (@inputData) { if ($inputLine =~ /$actualRegularExpression/) { print " Match: \"$inputLine\"\n"; } } } print "----- Fini ----------------------------\n";
Results:
D:\PerlMonks>regex1.pl ----- Without quotemeta --------------- Using regular expression /test.dat/: Match: "test.dat" Match: "testadat.exe" Using regular expression /test.exe/: Match: "test.exe" Match: "testaexe.dat" ----- With quotemeta ------------------ Using regular expression /test\.dat/: Match: "test.dat" Using regular expression /test\.exe/: Match: "test.exe" ----- Fini ---------------------------- D:\PerlMonks>
In reply to Re: Regex with variables
by marinersk
in thread Regex with variables
by cormanaz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |