in reply to Re: How to use \W in Regular Expression?
in thread How to use \W in Regular Expression?

So could you tell me how to highlight this word "perl" in above program?
  • Comment on Re^2: How to use \W in Regular Expression?

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

    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?

      I would like to use \W in the following program to ignore special character(:) after word "perl" in above example. and want to highlight only word "perl". So how can i do it?
      #!/usr/bin/perl -W $str = <STDIN>;# suppose $str = "i am perl: a system"; chomp($str); $query = <STDIN>;# suppose $query = 'perl'; chomp($query); #$query = "perl"; $str =~ s/$query\W+/<em>$query<\/em> \W+/ig; print " Value = " . $str;

        It'll ignore everything it doesn't match. You don't have to do anything.

        If $query contains a literal text to match:

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

        If $query contains a regex pattern:

        $str =~ s/($query)/<em>$1<\/em>/ig;

        ...like I've already said: get rid of the \W+ in the substitution string:

        $str =~ s/$query\W+/<em>$query<\/em> \W+/ig; ^^^

        The regex (i.e. s/$query\W+/) matches "perl: " which is then being substituted with the string "<em>$query</em> ".

        Update: on second read it seems you want to keep the ":" (-> "ignore")...  in which case just don't match it in the first place, as ikegami said below.

        What you may have had in mind could be written as

        $str =~ s/$query(\W+)/<em>$query<\/em>$1/ig;

        that is, $1 would re-insert into the substitution string whatever the captured part in the regex (\W+) matched (i.e. ": ").  But as already said, that's not necessary if you don't include it in the match in the first place.

        Sachin: Just out of curiosity: when you executed the code fragment in the OP with  -W 'no, really' warnings turned on, didn't you get a warning message?

        >perl -WMstrict -le
        "my $str = 'i am perl: a system';
         my $query = 'perl';
         $str =~ s/$query\W+/<em>$query<\/em> \W+/ig;
         print ' Value = ' . $str;
        "
        Unrecognized escape \W passed through at -e line 1.
         Value = i am <em>perl</em> W+a system

        This should have been a clue.