Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

up vote 1 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
    
@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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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