Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Regex with variables

by marinersk (Priest)
on Jun 30, 2015 at 00:46 UTC ( [id://1132547]=note: print w/replies, xml ) Need Help??


in reply to Regex with variables

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>

Replies are listed 'Best First'.
Re^2: Regex with variables
by AnomalousMonk (Archbishop) on Jun 30, 2015 at 01:44 UTC
    ... use quotemeta ...

    ... or  \Q$string\E its interpolative equivalent:

    c:\@Work\Perl\monks>perl -wMstrict -le "my @inputData = qw(test.dat test.exe testadat.exe testaexe.dat); ;; my @search_strings = qw(test.dat test.exe); ;; print '----- With quotemeta ------------------'; foreach my $search (@search_strings) { print qq{Using search string '\Q$search\E':}; foreach my $inputLine (@inputData) { if ($inputLine =~ m{ \Q$search\E }xms) { print qq{ Matched: '$inputLine'}; } } } " ----- With quotemeta ------------------ Using search string 'test\.dat': Matched: 'test.dat' Using search string 'test\.exe': Matched: 'test.exe'


    Give a man a fish:  <%-(-(-(-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1132547]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 17:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found