Contributed by Warped
on Oct 30, 2001 at 00:58 UTC
Q&A
> strings
Answer: How do I delete the last instance of a word from a string? contributed by suaveant substr($string,rindex($string,$word),length($word)) = '';
or, to avoid removing the last character of the string
when $word is not present:
my $ri = rindex($string,$word);
substr($string,$ri,length($word)) = '' if $ri > -1;
Edit by tye to incorporate reply | Answer: How do I delete the last instance of a word from a string? contributed by tye Although I prefer the rindex/substr solution, another alternative involves regular expressions with "zero-width negative look-ahead assertions":
s/\Q$word\E(?!.*\Q$word\E)//s
or, if you really only want "words":
s/\b\Q$word\E\b(?!.*\b\Q$word\E\b)//s
| Answer: How do I delete the last instance of a word from a string? contributed by Incognito 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.
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
Log In?
|
|
Chatterbox?
|
How do I use this? | Other CB clients
|
Other Users?
|
Others exploiting the Monastery: (5) As of 2021-02-27 19:07 GMT
|
Sections?
|
|
Information?
|
|
Find Nodes?
|
|
Leftovers?
|
|
Voting Booth?
|
No recent polls found
|
Notices?
|
|
|