Skip to content

Instantly share code, notes, and snippets.

@djpadz
Last active February 19, 2020 21:45
Show Gist options
  • Save djpadz/9eb640e7f54075903af3734ccdc9d607 to your computer and use it in GitHub Desktop.
Save djpadz/9eb640e7f54075903af3734ccdc9d607 to your computer and use it in GitHub Desktop.
PERL: Match a shell expression
#!/usr/bin/perl
sub shexp_match {
my $shexp = shift;
my $word = shift;
# Translate a shell expression into a regular expression
my $re = $shexp;
# Convert all .'s into quoted .
$re =~ s/\./'\.'/ge;
print "1. \"$re\"\n";
# Convert all unquoted *'s into .*
$re =~ s/(^|[^\\])\*/"${1}.*"/ge;
print "2. \"$re\"\n";
# Convert all unquoted ?'s into ?
$re =~ s/(^|[^\\])\?/"${1}."/ge;
print "3. \"$re\"\n";
# Convert {a,b,c} into (?:a|b|c)
while ($re =~ /(^|.*[^\\])\{(.*[^\\])?\}(.*)/) {
my ($before, $list, $after) = ($1, $2, $3);
$list =~ s/(^|[^\\]),/"${1}|"/ge;
$list = "(?:${list})";
$re = $before . $list . $after;
print $re, "\n";
}
# Anchor the expression
$re = "^${re}\$";
print qr{$re}, "\n";
return $word =~ qr{$re} ? 1 : 0;
}
print shexp_match('h{e,o,\}}ll{o,i}.exe', 'hello.exe');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment