Extract last word in string in R

前端 未结 5 1710
情深已故
情深已故 2020-11-29 05:53

What\'s the most elegant way to extract the last word in a sentence string?

The sentence does not end with a \".\" Words are seperated by blanks.

sen         


        
相关标签:
5条回答
  • 2020-11-29 06:19

    Going in the package direction, this is the simplest answer I can think of:

    library(stringr)
    
    x <- 'The quick brown fox'
    str_extract(x, '\\w+$')
    #[1] "fox"
    
    0 讨论(0)
  • 2020-11-29 06:22
    tail(strsplit('this is a sentence',split=" ")[[1]],1)
    

    Basically as suggested by @Señor O.

    0 讨论(0)
  • 2020-11-29 06:22

    Just for completeness: The library stringr contains a function for exactly this problem.

    library(stringr)
    
    sentence <- "The quick brown fox"
    word(sentence,-1)
    [1] "fox"
    
    0 讨论(0)
  • 2020-11-29 06:26

    Another packaged option is stri_extract_last_words() from the stringi package

    library(stringi)
    
    stri_extract_last_words("The quick brown fox")
    # [1] "fox"
    

    The function also removes any punctuation that may be at the end of the sentence.

    stri_extract_last_words("The quick brown fox? ...")
    # [1] "fox"
    
    0 讨论(0)
  • 2020-11-29 06:39
    x <- 'The quick brown fox'
    sub('^.* ([[:alnum:]]+)$', '\\1', x)
    

    That will catch the last string of numbers and characters before then end of the string.

    You can also use the regexec and regmatches functions, but I find sub cleaner:

    m <- regexec('^.* ([[:alnum:]]+)$', x)
    regmatches(x, m)
    

    See ?regex and ?sub for more info.

    0 讨论(0)
提交回复
热议问题