我正在寻找一种有效的方法来提取字符串中两个子字符串之间的所有匹配项。例如说我要提取字符串之间包含的所有子字符串
start="strt"
和
stop="stp"
in string
x="strt111stpblablastrt222stp"
我想得到向量
"111" "222"
在R中最有效的方法是什么?也许使用正则表达式?还是有更好的方法?
对于这样简单的事情,基数R可以很好地处理。
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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句