Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Matching parenthesis in a string

by ciamack (Novice)
on Oct 15, 2002 at 15:28 UTC ( [id://205399]=perlquestion: print w/replies, xml ) Need Help??

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

Hi
I have a script where I need to match strings with parenthesis to string items in an array. here is a part of it:
@array = ("text1_(Right):662:19990913:662:19990913:1", "text2(Right):8000:20020116:8000:20020116:1", "text3:6800:20021015:6900:20021014:1"); $Symbol= "text1_(Right)"; foreach $item (@array){ if ($item =~ m/$Symbol/i) { print "$item\n"; } }

If I try to match "(Right)" to items in the array, I'll get 2 matches but the way it is combined with some other text, even if the exact match exists in the array, as in the example, I don't get any results. There probably is something I ought to do, but I don't know what I am missing here.

I appreciate any help.
Thanks,
Ciamack

Edit by tye to add CODE tags and remove most BR tags

Replies are listed 'Best First'.
Re: Matching parenthesis in a string
by zigdon (Deacon) on Oct 15, 2002 at 15:32 UTC

    Since ()s are metachars for a regexp, you're actually matching "text1_Right" - which doesn't exist in your example. What you'll have to do is escape the ()s in your string:

    @array = ("text1_(Right):662:19990913:662:19990913:1", "text2(Right):8000:20020116:8000:20020116:1", "text3:6800:20021015:6900:20021014:1"); $Symbol= "text1_(Right)"; foreach $item (@array){ if ($item =~ m/\Q$Symbol/i) { print "$item\n"; } }

    See perlop for the use of \Q

    -- Dan

Re: Matching parenthesis in a string
by Abigail-II (Bishop) on Oct 15, 2002 at 15:33 UTC
    If you want to do exact matching, probably the simplest is to use index(). Or to "quote meta" your search pattern, with either quotemeta or \Q .. \E.

    Abigail

Re: Matching parenthesis in a string
by John M. Dlugosz (Monsignor) on Oct 15, 2002 at 19:37 UTC
    The easiest thing is to use \Q when interpolating the string into your regex operator.

    But why does that work? It changes ( to \(, etc. You would write m/\(Right\)/ normally. When interpolating, it's confusing because the backslashes are used by both the quote and the regex, and parens are not special to quotes. You would have to get a backslash into the regex, and that would require escaping that out in the quote! $Symbol= "\\(Right\\)".

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://205399]
Approved by krisahoch
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-19 20:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found