http://www.perlmonks.org?node_id=581980

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

Hi Monks,

I am having trouble with searching for a string with special characters.

When I have texts without 'brackets' in the SFile, I get the required result but it fails if I want to search for a string with 'brackets'. Could someone help me or point to some documentation? Thanks.

#! /path/to/perl use strict; open (MAINFILE, "./TestFile") or die "Can't find file"; open (SFILE, "./SFile") or die "Can't find file"; my $search; while (<SFILE>) { $search = $_; print "search string is $search"; } close ( SFILE ); print "Now opening the main file\n"; while (<MAINFILE>) { if ( ! /$search/ ) { print "No Match found\n"; next; } else { print "Found $search in main file"; } } TestFile: Bus Bus(Mini) Car Van SFile: Bus(Mini)

Replies are listed 'Best First'.
Re: Regex: Searching for a string with special characters
by liverpole (Monsignor) on Nov 02, 2006 at 23:28 UTC
    I assume by 'brackets' you mean parentheses? That is, '(' and ')'?

    Try using \Q ... \E in your regular expression if you want to 'escape' the string being searched against:

    if ( ! /\Q$search\E/ ) { print "No Match found\n"; next; }

    You can find more by reading perlre.

    And another option is to use the qr/\Q$search\E/ syntax, which you can find in perlop.

    Update:  Fixed wording (thanks for pointing that out, Hofmator++.)

    Good luck!


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      And another option is to use the qr/$string/ syntax, which you can find in perlop.

      Just a small annotation. This is only correct if it is supposed to be a general comment. The qr/$string/ construct has no influence on the escape issue whatsoever.

      For the escaping see also quotemeta.

      -- Hofmator

      Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        Thanks a lot.

        As mentioned by you, 'qr' didn't work for me but I was able to get the desired results using 'quotemeta'.

Re: Regex: Searching for a string with special characters
by GrandFather (Saint) on Nov 02, 2006 at 23:32 UTC

    you may also want to remove line ends (chomp).

    Update: note that your sample would be better given as follows to avoid external files:

    use warnings; use strict; my $search = "Bus(Mini)\n"; while (<DATA>) { if ( ! /$search/ ) { print "No Match found\n"; next; } else { print "Found $search in main file\n"; } } __DATA__ TestFile: Bus Bus(Mini) Car Van

    DWIM is Perl's answer to Gödel