Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

How to use \W in Regular Expression?

by Sachin (Acolyte)
on Dec 30, 2009 at 12:02 UTC ( [id://814920]=perlquestion: print w/replies, xml ) Need Help??

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

I would like to use \W in the following program to ignore special character. But it prints "i am perl W+a system"
#!/usr/bin/perl -W $str = "i am perl: a system"; $query = "perl"; $str =~ s/$query\W+/<em>$query<\/em> \W+/ig; print " Value = " . $str;

Replies are listed 'Best First'.
Re: How to use \W in Regular Expression?
by almut (Canon) on Dec 30, 2009 at 12:08 UTC

    The substitution part of s/// is not a regular expresssion, so it doesn't make much sense to put \W+ in there.  Just remove it:

    $str =~ s/$query\W+/<em>$query<\/em> /ig;
      So could you tell me how to highlight this word "perl" in above program?

        Not sure what you mean. There's no problem with adding <em>...</em> around the word "perl", it's just the \W+ that's inappropriate in the string to substitute...

        Think of it this way: What concrete characters (and how many) should be substituted from the class of characters that \W stands for?

Re: How to use \W in Regular Expression?
by ikegami (Patriarch) on Dec 30, 2009 at 14:29 UTC

    Is your question really about how to prevent $query="perl"; from matching anything in "This drink is fraperliscious!"?

    $str =~ s/\b\Q$query\E\b/<em>$query<\/em>/ig;

    or

    $str =~ s/(?<!\w)\Q$query\E(?!\w)/<em>$query<\/em>/ig;
Re: How to use \W in Regular Expression?
by gube (Parson) on Dec 30, 2009 at 15:25 UTC

    \W means Match non-word character. As almut said its not required for replace what you are trying to do. Just s/$query/<em>$query</em>/i would be fine. Perl regex

Log In?
Username:
Password:

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

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

    No recent polls found