Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Match last word in a sentence

by haukex (Archbishop)
on Aug 15, 2021 at 10:20 UTC ( [id://11135851]=note: print w/replies, xml ) Need Help??


in reply to Match last word in a sentence

Two things that haven't been mentioned yet:

I guess the regular expression needs to start from right to left correct?

The regex engine always operates from left to right. The solutions provided here using the $ anchor don't change that - the regex engine is still operating from left to right, but it's only matching on the last word because of the anchor.

Trying to get the last word in a sentence

Note that "This is my list" is missing punctuation. It's unclear from your question if your sentences are already split, but if you were to process text like "I took the medicine that Dr. Wall recommended to me. It tasted like onions.", you'd want that to be split into two sentences, not three - modules like Lingua::Sentence will do that for you.

use warnings; use strict; use Lingua::Sentence; use Data::Dump; my $text = "I took the medicine that Dr. Wall recommended to me. It ta +sted like onions."; my $splitter = Lingua::Sentence->new("en"); my @sentences = $splitter->split_array($text); dd @sentences; for my $sentence (@sentences) { if ( $sentence =~ /\s(\w+)[^\w\s]?$/ ) { dd $1; } else { warn "Failed to get last word from: $sentence" } } __END__ ( "I took the medicine that Dr. Wall recommended to me.", "It tasted like onions.", ) "me" "onions"

(This uses the somewhat simplistic [^\w\s] to try and match any final punctuation, it may need to be adjusted depending on the input data.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-03-28 13:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found