Perl: Regex, string matching

Hi,

I've a logfile which i need to parse and get the logs depending upon the user input. here, i'm providing an option to enter the string which can be matched with the log entries.

e.g. one of the logfile entry reads like this -

$str = "[latency][info] mpgw(BLUESOAPFramework): trans(24578291)[152.32.174.110]:Latency: 0 14 0 13 14 13 0 178 183 178 183 184 183 178 13 14 "

Now, if the user provides the string to be matched as '24578291' or 'BLUESOAPFrameworkV001' then it matches correctly
but if it includes characters (, ), [, ], / etc then it doesnt matches.

i'm matching the string as below -

$str =~ m/[latency][info] mpgw(BLUESOAPFramework/

The errors i receive are as below

Unmatched ( in regex; marked by <-- HERE in m/[latency][info] mpgw( <-- HERE BLUESOAPFramework/ at (eval 12)[/usr/lib/perl5/5.8.5/perl5db.pl:620] line 2.
at (eval 12)[/usr/lib/perl5/5.8.5/perl5db.pl:620] line 2
eval '($@, $!, $^E, $,, $/, $\\, $^W) = @saved;package main; $^D = $^D | $DB::db_stop;
$str =~ m/[latency][info] mpgw(BLUESOAPFramework/;
;' called at /usr/lib/perl5/5.8.5/perl5db.pl line 620
DB::eval called at /usr/lib/perl5/5.8.5/perl5db.pl line 3292
DB::DB called at -e line 1

Can someone please help?
Thanks in advance.

You're using special characters like the parentheses, escape it to avoid the special meaning:

$str =~ m/[latency][info] mpgw\(BLUESOAPFramework/;

But i can't skip it with escape character as the string to be matched is entered by the user and if it has special characters then the problem comes..i dont knw the user i/p in advance....let me know if i didnt understand wht you said.

Ok , try something like this:

$str = "[latency][info] mpgw(BLUESOAPFramework): trans(24578291)[152.32.174.110]:Latency: 0 14 0 13 14 13 0 178 183 178 183 184 183 178 13 14 ";

$userInput = "[latency][info] mpgw(BLUESOAPFramework";

$userInput =~ s/(\(|\)|\[|\])/\\\1/g;

print "trans usrInput: $userInput\n";

if ( $str =~ m/$userInput/ ) {
   print $str."\n";
   }

Thanks Klashxx :slight_smile:
Tht worked perfectly. Thnx again.

Another option would be to use quotemeta i.e.

my $userInput = "[latency][info] mpgw(BLUESOAPFramework";
$userInput = quotemeta($userInput);

print "trans usrInput: $userInput\n";
if ( $str =~ m/$userInput/ ) {
   print $str."\n";
}
2 Likes

Nice one! thanks!