Home: Perl Programming Help: Regular Expressions:
Comparing two strings, ignoring a specific character



peol
New User

Mar 26, 2013, 3:12 PM


Views: 18098
Comparing two strings, ignoring a specific character

If i have the following defined:

$string = "ABCD";

$comp = "ABC*E";

$comp2 = "*BC*E";

How can i treat the "*" character in $comp as a wildcard for the character at that specific position, so that $string and $comp is considered as equal? In the same way $string and $comp2 should also be considered as equal.


Kenosis
User

Mar 26, 2013, 6:38 PM


Views: 18092
Re: [peol] Comparing two strings, ignoring a specific character

One way would be to substitute the "*" with a "." and do a match, like the following:


Code
print "Same\n" if $string =~ /^ABC.E\z/;


You can see that the match is hard coded, so is not too helpful except to illustrate that the "." in a regex will match any char (almost :). However, the order of strings becomes a bit more complicated when comparing $comp and $comp2, since the latter has to be in // for the matching to succeed.

All of this can be taken care of in a subroutine to which you send any two of these strings to do a comparison test using 'wild-card' characters:


Code
use strict; 
use warnings;

my $string = "ABCDE";
my $comp = "ABC*E";
my $comp2 = "*BC*E";

print "Same\n" if wildSame( $string, $comp );
print 'Same' if wildSame( $string, $comp2 );

sub wildSame {
s/\*/./g for @_;

my ( $var1, $var2 );
my $count1 = $_[0] =~ tr/.//;
my $count2 = $_[1] =~ tr/.//;

if ( $count1 < $count2 ) {
$var1 = $_[0];
$var2 = $_[1];
}
else {
$var1 = $_[1];
$var2 = $_[0];
}

return $var1 =~ /^$var2\z/;
}


Output:


Code
Same 
Same


The subroutine first globally replaces any "*" with "." and then counts the number of "." in each of the two strings, so the one with more "." ends up in //.

Hope this helps!


peol
New User

Mar 27, 2013, 5:42 AM


Views: 18083
Re: [Kenosis] Comparing two strings, ignoring a specific character

Thanks!!


Kenosis
User

Mar 27, 2013, 8:49 AM


Views: 18079
Re: [peol] Comparing two strings, ignoring a specific character

You're most welcome!