Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Grep strings with special characters

by baski (Novice)
on Sep 13, 2010 at 06:36 UTC ( [id://859944]=perlquestion: print w/replies, xml ) Need Help??

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

How to grep strings with special characters?
#! /usr/bin/perl my $url="<Url><![CDATA[http://abc.com/search?q=perl+grep+&ie=utf8&oe=u +tf8&aq=t]></Url>"; my $str="dog"; my @f=("dog","<Url><![CDATA[http://abc.com/search?q=perl+grep+&ie=utf8 +&oe=utf8&aq=t]></Url>"); if(grep{/$url/}@f){print "Match!!\n";} else {print "No match\n";}
The result is :

No match.

Replies are listed 'Best First'.
Re: Grep strings with special characters
by prasadbabu (Prior) on Sep 13, 2010 at 06:50 UTC
Re: Grep strings with special characters
by suhailck (Friar) on Sep 13, 2010 at 07:42 UTC
    Try

    grep{/\Q$url\E/}@f

Re: Grep strings with special characters
by CountZero (Bishop) on Sep 13, 2010 at 14:14 UTC
    To expand on what the Monks above already told you, the reason why your regular expression does not match is because it contains metacharacters, i. e. the characters \ . ^ $ * + ? { } [ ] ( ) |

    If you want to match on any of them you need to escape them, i.e. put a backslash in front of each of them, but you can spare yourself the trouble by using the quotemeta function on the regex-string.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Grep strings with special characters
by repellent (Priest) on Sep 13, 2010 at 18:01 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-18 11:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found