Regular expression in R to remove the part of a string after the last space

后端 未结 2 1911
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 06:20

I would like to have a gsub expression in R to remove everything in a string that occurs after the last space. E.g. string=\"Da Silva UF\" should r

相关标签:
2条回答
  • 2021-01-20 06:32

    You can use the following.

    string <- 'Da Silva UF'
    gsub(' \\S*$', '', string)
    
    [1] "Da Silva"
    

    Explanation:

                ' '
    \S*         non-whitespace (all but \n, \r, \t, \f, and " ") (0 or more times)
      $         before an optional \n, and the end of the string
    
    0 讨论(0)
  • 2021-01-20 06:41

    Using $ anchor:

    > string = "Da Silva UF"
    > gsub(" [^ ]*$", "", string)
    [1] "Da Silva"
    
    0 讨论(0)
提交回复
热议问题