开发者

searching for parentheses in perl

Writing a program where I read in a list of words/symbols from one file and search for each one in another body of text.

So it's something like:

while(<FILE>){
    $findword = $_;

    for (@text){
        if ($_=~ /$find/){
            push(@found, $_);
        }
    }
}

However, I run into trouble once parentheses show up. It gives me this error:

Unmatch开发者_JS百科ed ( in regex; marked by <-- HERE in m/( <-- HERE

I realize it's because Perl thinks the ( is part of the regex, but how do I deal with this and make the ( searchable?


You could use \Q and \E:

if ($_ =~ /\Q$find\E/){

Or just use index if you're just looking for a literal match:

if(index($_, $find) >= 0) {


In general backslash escapes characters inside regexes - i.e. /\(/ will match a literal (

in situations like this it's better to use the quote operator

if ( $_ =~ /\Q$find\E/ ) {
    ...
}

alternatively use quotemeta


You'll want to do /\Q$find\E/ instead of just /$find/ - the \Q tells the parser to stop considering metacharacters as part of the regex until it finds the \E.


I suspect you will find m/\Q$find\E/ useful - unless you want other Perl regex metacharacters to be interpreted as metacharacters.


\Q with \e will escape your special chars in the $find variable like:

while(<FILE>){
    $findword = $_;

    for (@text){
        if ($_=~ /\Q$find\e/){
            push(@found, $_);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜