是否有R函数提取所有数字后跟特定模式?

问题描述 投票:0回答:2

我正在工作R.我想在向量中提取最后一个空格和字符串模式(“-APPLE”)之间的所有数字。数字可以是可变长度的。

test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE", "ORANGE")

预期结果集应为c中的向量(2,25,567,NA)

r string extraction
2个回答
1
投票

有关使用Regex group capture in R with multiple capture-groups包中的str_match()的示例,请参阅stringr

在你的情况下:

> test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE")
> 
> library(stringr)
> x <- str_match(test_string, " ([0-9]+)-APPLE$")[,2]
> as.numeric(x)
[1]   2  25 567

1
投票

你可以使用“rebus”软件包,它非常人性化,可以创建你需要的正则表达式模式。

library(rebus)
## adjust the lo and hi arguments of dgt() based on your text

rx <- lookbehind(SPACE) %R% dgt(1,5) %R% lookahead("-APPLE")
str_extract(test_string, rx)
© www.soinside.com 2019 - 2024. All rights reserved.