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 (Pope) 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;


    $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