简体   繁体   中英

Perl: Regular Expression Matching

Say I have a fixed variable:

$f_variable = "hello.exe";

and I want to search through a file line by line and find the path that contains this word, for example:

/Desktop/Downloads/hello.exe

or

/Desktop/Downloads/hello_qwdqd.exe

Lets say that the file extension can be either exe or ex

and i wrote this line of code:

 if ($line =~ m/(\/$f_variable.*\.[exe]+)

obviously it won't works because the line of code above is actually:

if ($line =~ m/(\/hello.exe.*\.[exe]+)

which will not match anything.

So my question is what changes should I make in order to match and capture the whole path properly without changing the value of $f_variable ?

What you wrote isn't even a complete regex. Though you've not said clearly what's in the file (Are the lines just paths?), you probably want something like:

my $pattern = $f_variable;
$pattern =~ s/\.exe?$//;
if ($line =~ m{(/\S*\Q$pattern\E[^/]*\.exe?)}) {
  print "$1\n";
}

This removes the file name .ex or .exe suffix to get the base name, then matches the first string that contains the base name including any non-space leading characters and trailing non-space characters ending in .ex or .exe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM