我正在寻找一种有效的方法来提取字符串中两个子字符串之间的所有匹配项。例如。说我想提取字符串之间包含的所有子字符串
start="strt"
和
stop="stp"
in string
x="strt111stpblablastrt222stp"
我想得到矢量
"111" "222"
在 R 中执行此操作的最有效方法是什么?也许使用正则表达式?或者有更好的方法吗?
最佳答案
对于像这样简单的事情,base R 处理得很好。
您可以打开 PCRE通过使用 perl=T
并使用 lookaround断言。
x <- 'strt111stpblablastrt222stp'
regmatches(x, gregexpr('(?<=strt).*?(?=stp)', x, perl=T))[[1]]
# [1] "111" "222"
说明 :
(?<= # look behind to see if there is:
strt # 'strt'
) # end of look-behind
.*? # any character except \n (0 or more times)
(?= # look ahead to see if there is:
stp # 'stp'
) # end of look-ahead
编辑:根据新语法更新了以下答案。
您也可以考虑使用 stringi 包。
library(stringi)
x <- 'strt111stpblablastrt222stp'
stri_extract_all_regex(x, '(?<=strt).*?(?=stp)')[[1]]
# [1] "111" "222"
和
rm_between
来自 qdapRegex 包。library(qdapRegex)
x <- 'strt111stpblablastrt222stp'
rm_between(x, 'strt', 'stp', extract=TRUE)[[1]]
# [1] "111" "222"
关于regex - R:提取包含在两个子字符串之间的所有子字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773737/