Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String match issue 2

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
0
0
US
Please take a look at the small sample code here.
I just don't understand why it actually finds a match!!

Code:
#!/usr/bin/perl -w

my $str = "group=1,101,102";
my $ip = "1.1.1.1";
if($str =~ /$ip/) {
  print "The string contains this IP!!\n"
}
else {
  print "The string does not contain this IP!!\n"
}
print "String: #$str#\n";
print "    IP: #$ip#\n";
exit;

Sample run:
Code:
./test.pl 
The string contains this IP!!
String: #group=1,101,102#
    IP: #1.1.1.1#

Thanks for your time and help!!
 
The periods need to be escaped. Right now, they are matching any character (which includes , 0 ,). Try it with this:
Code:
#!/usr/bin/perl -w

my $str = "group=1,101,102";
my $ip = '1\.1\.1\.1';
if($str =~ /$ip/) {
  print "The string contains this IP!!\n"
}
else {
  print "The string does not contain this IP!!\n"
}
print "String: #$str#\n";
print "    IP: #$ip#\n";
exit;
Note, i have switched the double quotes to single quotes, so I did not have to escape the escape character. I have not tested this, so feel free to come back with problems.
 
Use \Q...\E to escape regular expression special characters, like the any character '.'

Also use word boundaries \b so that you don't match a substring like 1.1.1.100

Code:
use strict;
use warnings;

my $str = "group=1,101,102";
my $ip = "1.1.1.1";

if ($str =~ /\b\Q$ip\E\b/) {
	print "The string contains this IP!!\n"

} else {
	print "The string does not contain this IP!!\n"
}

print "String: #$str#\n";
print "    IP: #$ip#\n";
exit;

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top