Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
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
up vote 6 down vote accepted

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.

share|improve this answer
    
Thanks, I forgot about \w. – OverTheRainbow Oct 31 '12 at 10:38
    
You could also use [a-zA-Z0-9] or similar, of course. – slhck Oct 31 '12 at 10:41
1  
\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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .