11

I can't find a way to extract the final word on a line, such as this:

^This is a sentence$

I'd like to extract just "sentence". Does someone have an idea?

Thank you.

2 Answers2

20

If the final word is preceded by a space, all you need is:

\s(\w+)$

The last word in the sentence will then be captured.

slhck
  • 228,104
  • You could also use [a-zA-Z0-9] or similar, of course. – slhck Oct 31 '12 at 10:41
  • 2
    \w is actually equal to [a-zA-Z0-9_] (note the underscore). Perhaps adding - (hyphen) might be useful for sentences like This has to be re-evaluated. – speakr Oct 31 '12 at 10:45
  • @slhck Your regex works very well except it also selects the white space before sentence. Omitting \s provides the exact result required by OP (extracting only sentence). Modification result: (\w+)$ – Ugo Dec 07 '13 at 14:44
  • 2
    @Ugo True, but the \s is outside the match group, so if you take match group results only, there is no difference. – slhck Dec 07 '13 at 14:51
  • 1
    how about everything except the last word of a sentence? – tggagne Nov 17 '15 at 02:38
  • 1
    @tggagne (.+)\b\w+$ would do that. – slhck Nov 17 '15 at 10:34
0

This worked for me:

(.*) ([^ ]+)$

Replace that with \2 that will give you the last word