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

后端 未结 2 1926
伪装坚强ぢ
伪装坚强ぢ 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
    

提交回复
热议问题