我正在工作R.我想在向量中提取最后一个空格和字符串模式(“-APPLE”)之间的所有数字。数字可以是可变长度的。
test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE", "ORANGE")
预期结果集应为c中的向量(2,25,567,NA)
有关使用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
你可以使用“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)