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

Replies are listed 'Best First'.
Re: exact search and replace
by Trimbach (Curate) on Mar 09, 2002 at 20:12 UTC
    the \b modifier is your friend. It will match on word boundries, a zero-width assertion that will match the "Samn" in "Samn's" but not the "Charisma" is "Charismatic." i.e.
    $def =~ s/\b$word\b/ <a href=$me\?word=$word>$entry[0]<\/a>/i;

    Gary Blackburn
    Trained Killer

Re: exact search and replace
by Juerd (Abbot) on Mar 09, 2002 at 20:13 UTC

    How can I make a more perfect search and replace, that replaces only words surrounded by white space or by a punctuation mark or marks?

    Use \b, that matches null strings at word boundaries. It's described in perlre, but has examples in perlretut:

    An anchor useful in basic regexps is the word anchor "\b". This matches a boundary between a word character and a non-word character "\w\W" or "\W\w":
    $x = "Housecat catenates house and cat"; $x =~ /cat/; # matches cat in 'housecat' $x =~ /\bcat/; # matches cat in 'catenates' $x =~ /cat\b/; # matches cat in 'housecat' $x =~ /\bcat\b/; # matches 'cat' at end of string
    Note in the last example, the end of the string is considered a word boundary.

    44696420796F7520732F2F2F65206F
    7220756E7061636B3F202F6D736720
    6D6521203A29202D2D204A75657264
    

Re: exact search and replace
by Cody Pendant (Prior) on Mar 10, 2002 at 01:35 UTC
    >words surrounded by white space or by a punctuation mark or marks?

    Just a note -- when is a punctuation mark not a punctuation mark?

    It's useful to note what exactly \b means. If you have hyphenated words, for instance, like say one of the people involved is called Sara-Jane, then will it work?

    --

    ($_='jjjuuusssttt annootthhrer pppeeerrrlll haaaccckkeer')=~y/a-z//s;print;