使用stringr查找文本中的最后数字
尝试使用StringR查找文本末尾的所有数字 比如说使用stringr查找文本中的最后数字,r,stringr,R,Stringr,尝试使用StringR查找文本末尾的所有数字 比如说 x <- c("Africa-123-Ghana-2", "Oceania-123-Sydney-200") 我相信可能有多种方法,但最好的代码是什么 谢谢。你可以用 sub(".*-(\\d+)$", "\\1", x) #[1] "2" "200" 或 或 你可以用 sub(".*-(\\d+)$", "\\1", x) #[1] "2" "200" 或 或 我们可以在base R中使用regexpr/regmatch
x <- c("Africa-123-Ghana-2", "Oceania-123-Sydney-200")
我相信可能有多种方法,但最好的代码是什么
谢谢。你可以用
sub(".*-(\\d+)$", "\\1", x)
#[1] "2" "200"
或
或
你可以用
sub(".*-(\\d+)$", "\\1", x)
#[1] "2" "200"
或
或
我们可以在
base R
中使用regexpr/regmatches
来匹配字符串末尾($
)的一个或多个数字(\\d+
)
regmatches(x, regexpr("\\d+$", x))
#[1] "2" "200"
或者使用
sub
,我们匹配字符直到最后一个不是数字的字符,并替换为空白(“”
)
或者使用
strsplit
sapply(strsplit(x, "-"), tail, 1)
#[1] "2" "200"
或者使用
stringr
与stru匹配
library(stringr)
str_match(x, "(\\d+)$")[,1]
#[1] "2" "200"
或使用str\u删除
str_remove(x, ".*\\D+")
#[1] "2" "200"
我们可以在
base R
中使用regexpr/regmatches
来匹配字符串末尾($
)的一个或多个数字(\\d+
)
regmatches(x, regexpr("\\d+$", x))
#[1] "2" "200"
或者使用
sub
,我们匹配字符直到最后一个不是数字的字符,并替换为空白(“”
)
或者使用
strsplit
sapply(strsplit(x, "-"), tail, 1)
#[1] "2" "200"
或者使用
stringr
与stru匹配
library(stringr)
str_match(x, "(\\d+)$")[,1]
#[1] "2" "200"
或使用str\u删除
str_remove(x, ".*\\D+")
#[1] "2" "200"
您尝试过您这边的内容吗?是的,我尝试过使用str_-match,但我猜无法找到反向(从右到左)查找。您应该分享您尝试过的内容。str_-match(x,“^(\\d+))您尝试过您这边的内容吗?是的,我尝试过使用str_-match,但我猜无法找到反向(从右到左)查找。您应该共享您尝试过的内容。str_match(x,“^(\\d+)”)