CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



peol
New User

Mar 26, 2013, 3:12 PM

Post #1 of 4 (11906 views)
Comparing two strings, ignoring a specific character Can't Post

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

Post #2 of 4 (11900 views)
Re: [peol] Comparing two strings, ignoring a specific character [In reply to] Can't Post

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

Post #3 of 4 (11891 views)
Re: [Kenosis] Comparing two strings, ignoring a specific character [In reply to] Can't Post

Thanks!!


Kenosis
User

Mar 27, 2013, 8:49 AM

Post #4 of 4 (11887 views)
Re: [peol] Comparing two strings, ignoring a specific character [In reply to] Can't Post

You're most welcome!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives