sjaaq has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I have a problem matching a string "-(lala)-" with regex. I have tried to escape the string like this: -\(lala\)- , that didn't work out either. Hope someone can help me. thanks!
$file ="-(lala)-"; $skip ="-(lala)-"; print "$skip / $file\n"; if ($file =~ /$skip/i) { print "matched!\n"; }

Replies are listed 'Best First'.
Re: Regex matchin -(lala)- problem
by zigdon (Deacon) on Oct 16, 2002 at 17:25 UTC
    You have to quote the () in $skip, otherwise they're parsed as part of the regexp:
    $file ="-(lala)-"; $skip ="-(lala)-"; print "$skip / $file\n"; if ($file =~ /\Q$skip\E/i) { print "matched!\n"; }

    See quotemeta. You could also use \ if your pattern is static, just watch out for the double quotes eating it up:

    $skip = "-\(lala\)-"; # $skip is now -(lala)- compared with $skip = '-\(lala\)-'; # $skip is now -\(lala\)-

    -- Dan

Re: Regex matchin -(lala)- problem
by bigj (Monk) on Oct 16, 2002 at 17:32 UTC
    if ($file =~ /-\(lala\)-/) { ...
    will work, but
    my $skip = "/-\(lala\)-/"; if ($file =~ /$skip/)
    won't work. The reason is the difference where the backslash is used. In the first case it is used in a regexp, where it protects the (), while in the second one, it is used in a string where it is interpreted as a simple () used in the regexp again as capturing characters. You can use one of the following workarounds:
    my $skip = "/-\\(lala\\)-/"; # protect the backslash for itself if ($file =~ /$skip/) { ...
    my $skip = '/-\(lala\)-/'; # use singe quotes if ($file =~ /$skip/) { ...
    my $skip = "/-(lala\-/"; if ($file =~ /\Q$skip/) { ... # quote it in the regexp
    my $skip = qr/-\(lala\)-/; # use precompiled regexps if ($file =~ /$skip/) { ...

    Greetings,
    Janek