Home: Perl Programming Help: Intermediate:
Wildcard string matching


Feb 8, 2001, 12:29 AM

Views: 1186
Wildcard string matching

I am trying to create a simple string matching subroutine that can match a string of wildcards (* and ?) to another string e.g. if...

$String is 'abc.test.com'
$Mask is '*.test.c?m'

the subroutine would return 1 as there is a match

but if the mask was '???.co.*' there would be no match and it would return 0

any help much appreciated


Feb 8, 2001, 8:30 AM

Views: 1183
Re: Wildcard string matching

The simplest thing to do is create a mapping of * and ? to Perl's regex notation:

%map = ( 
'*' => '.*',
'?' => '.',

# now, convert characters as needed
$pattern =~ s/(\W)/$map{$1} || "\\$1"/eg;

if ($domain =~ /$pattern/) { match }

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author