首页 > 解决方案 > 如何获取最后一个逗号后的文本?

问题描述

我有一个文本,说:

s <- "Chengdu Shi, Sichuan Sheng, China"

我想使用一个函数,这样我只会得到最后一个逗号之后的单词(即中国)。

我尝试了几种方法,例如 grep,但它们返回所有实例而不是最后一个。

标签: rsubstring

解决方案


使用sub

# Simply get the text after last comma ,
sub('.*\\,', '', s)

或者

wordlibrary(stringr)包中使用:

s <- "Chengdu Shi, Sichuan Sheng, China"
word(s,3,sep=",") # Extract word from the last column

或者

# If your data is stored in data.frame
word(s,ncol(s),sep=",") # Extract last column data using column index

输出:

[1] " China"

推荐阅读