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

≯℡__Kan透↙ 提交于 2019-12-04 04:02:14

问题


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 return me "Da Silva". Any thoughts?


回答1:


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



回答2:


Using $ anchor:

> string = "Da Silva UF"
> gsub(" [^ ]*$", "", string)
[1] "Da Silva"


来源:https://stackoverflow.com/questions/20497895/regular-expression-in-r-to-remove-the-part-of-a-string-after-the-last-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!