Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How do I delete the last instance of a word from a string?

by Incognito (Pilgrim)
on Nov 07, 2001 at 03:08 UTC ( [id://123722]=note: print w/replies, xml ) Need Help??


in reply to How do I delete the last instance of a word from a string?

tye's regex solution works well, but you may want to modify it to:
$sentence =~ s/\b\Q$word\E\b\s+(?!.*\b\Q$word\E\b)//s;
to elimitate the extra space that's left when the word is removed. This leaves us with:
String: the quick brown dog jumped the doggy style dog killing doggie +eater. Result: the quick brown dog jumped the doggy style killing doggie eate +r.
where the $word = "dog".

(Added by tye) Note that if the last occurance of that word is also the last word of a sentence, it will have whitespace in front of it and not behind it and this regex will fail. If the last occurance of the word is unlikely to be the first word in the string, then

$sentence =~ s/\s*\b\Q$word\E\b(?!.*\b\Q$word\E\b)//s;
would be a better choice.

Replies are listed 'Best First'.
Re: Answer: How do I delete the last instance of a word from a string?
by blakem (Monsignor) on Nov 07, 2001 at 03:36 UTC
    Perhaps a slight change is necessary... Consider:

    'Go walk the dog'

    -Blake

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 17:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found