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.

  • Does your sentence literally include ^ and $? – slhck Oct 31 '12 at 10:30
  • No, it was just meant to show that it's on a line by itself. Using " (.+)?$" doesn't work, as it takes the second word until the end of the line. – OverTheRainbow Oct 31 '12 at 10:31

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


The last word in the sentence will then be captured.

  • 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 7 '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 7 '13 at 14:51
  • 1
    how about everything except the last word of a sentence? – tggagne Nov 17 '15 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.