use v5.12; # https://perlmonks.org/?node_id=11146744 use warnings; use Data::Dump qw/pp dd/; #pp my ($paths,$cmds) = data(); my $re = join "|", map {"\Q$_\E" } @$paths; for my $cmd (@$cmds) { my @matches; $cmd =~ m{ ^CMD=" ($re) #/? # final / is missing (?!\.) # no empty name before .extension ([^/]+) "$ (?{push @matches,[$1,$2]}) (*FAIL) }x; pp {$cmd => \@matches}; } sub data { return [ qw( /a /a/b /a/b/c /b /b/c /c /ab /abc /abcd )] , [ qw( CMD="/a/a.sh" CMD="/aa.sh" CMD="/ab.sh" CMD="/abc.sh" CMD="/a/bc.sh" CMD="/a/b/c.sh" CMD="/a/b/c/.sh" CMD="/a/b/cd.sh" CMD="/a/b/c/d.sh" CMD="/x/y.z" CMD="/a/xyz.sh" CMD="/abcd.sh" ), q(CMD="/a/very 'special' command.exe") ] }