Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to find last word in sentence

How can I find last word in a sentence with a regular expression?

like image 940
Sam Avatar asked Sep 05 '10 22:09

Sam


People also ask

How do you get the last word in a string in python?

Take an empty string, newstring. Traverse the string in reverse order and add character to newstring using string concatenation. Break the loop till we get first space character. Reverse newstring and return it (it is the last word in the sentence).

What is b regex?

The \b metacharacter matches at the beginning or end of a word.


2 Answers

If you need to find the last word in a string, then do this:

m/
    (\w+)      (?# Match a word, store its value into pattern memory)

    [.!?]?     (?# Some strings might hold a sentence. If so, this)
               (?# component will match zero or one punctuation)
               (?# characters)

    \s*        (?# Match trailing whitespace using the * because there)
               (?# might not be any)

    $          (?# Anchor the match to the end of the string)
/x;

After this statement, $1 will hold the last word in the string. You may need to expand the character class, [.!?], by adding more punctuation.

in PHP:

<?php

$str = 'MiloCold is Neat';
$str_Pattern = '/[^ ]*$/';

preg_match($str_Pattern, $str, $results);

// Prints "Neat", but you can just assign it to a variable.
print $results[0];

?> 
like image 73
Moin Zaman Avatar answered Sep 29 '22 23:09

Moin Zaman


In general you can't correctly parse English text with regular expressions.

The best you can do is to look for some punctuation that usually terminates a sentence but unfortunately this is not a guarantee. For example the text Mr. Bloggs is here. Do you want to talk to him? contains two periods which have different meanings. There is no way for a regular expression to distinguish between the two uses of the period.

I'd suggest instead that you look at a natural language parsing library. For example the Stanford Parser has no trouble at all correctly parsing the above text into the two sentences:

Mr./NNP Bloggs/NNP is/VBZ here/RB ./.
Do/VBP you/PRP want/VB to/TO talk/VB to/TO him/PRP ?/.

There are lots of other freely available NLP libraries that you could use too, I'm not endorsing that one product in particular - it's just an example to demonstrate that it is possible to parse text into sentences with a fairly high reliability. Note though that even a natural language parsing library will still occasionally make a mistake - parsing human languages correctly is hard.

like image 40
Mark Byers Avatar answered Sep 30 '22 01:09

Mark Byers