开发者

Using variables that contain special characters in Perl regexes

开发者 https://www.devze.com 2023-03-13 04:15 出处:网络
I\'m trying to search an array for lines that contain $inbucket[0].Some of my $inbucket[0] values include special characters.This script does exactly what I want it to, until I hit a special character

I'm trying to search an array for lines that contain $inbucket[0]. Some of my $inbucket[0] values include special characters. This script does exactly what I want it to, until I hit a special character.

I want the query to be case insensitive, match any part of the string $var, and process the special characters literally, as if they weren't special. Any ideas?

Thanks!

sub loopthru() {
    warn "Loopthru 开发者_StackOverflow社区begun on $inbucket[0]\n";
    foreach $c (@chat) {
        $var = $c->msg;
        $lookfor2 = $inbucket[0];
        if ( $var =~ /$lookfor2/i ) {
            ($to,$from) = split('-',$var);
            $from =~ s/\.$//;
            print MYFILE "$to\t$from\n";
            &fillbucket($to);
            &fillbucket($from);
        }
    }
}


You can use quotemeta, which returns the value of its argument with all non-"word" characters backslashed.

$lookfor2 = quotemeta $inbucket[0];

Or you can use the \Q escape, which is discussed in perlre. In short, it will quote (disable) pattern metacharacters until \E is encountered.

if ( $var =~ /\Q$lookfor2/i ) {


I think you are looking for $var =~ /\Q$lookfor2/i

perl faq

0

精彩评论

暂无评论...
验证码 换一张
取 消