Extract last word in a string after comma if there are multiple words else the first word

老子叫甜甜 提交于 2019-12-05 08:20:32

You can try sub

 df$country <- sub('.*,\\s*', '', df$location)
 df$country
 #[1] "New Zealand" "USA"         "France"   

Or

 library(stringr)
 str_extract(df$location, '\\b[^,]+$')
 #[1] "New Zealand" "USA"         "France"     

stringi solution:

require(stringi)
location<- c("xyz, sss, New Zealand", "USA", "Pris,France")
stri_trim(stri_match_first_regex(location, "(^|,)([^,]*?)$")[,3])
## [1] "New Zealand" "USA"         "France"  

stri_trim removes unnecessary spaces before/after country name.

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