我想找到某个字符串中匹配模式的所有索引。例如,我有一个字符串 x <- "1110001101"
,我想将它与"11"
相匹配,结果应该是 c(1, 2, 7)
,但是,我就是无法得到 2
...
方法一:使用
gregexpr
x [1] "1110001101" gregexpr(pattern = "11", x) [[1]] [1] 1 7 # Why isn't there a 2? attr(,"match.length") [1] 2 2 attr(,"useBytes") [1] TRUE
方法 2:使用
str_locate_all
从包装stringr
library(stringr) str_locate_all(pattern = "11", x) [[1]] start end [1,] 1 2 [2,] 7 8 # Why still isn't there a 2?
我是否丢失了这些函数的一些微妙参数?感谢您的建议!
最佳答案
我们可以使用正则表达式环视,即正则正则表达式环视来匹配后跟两个 1 的字符,以给出与 gregexpr
匹配的开始位置
as.integer(gregexpr("(?=11)", x, perl = TRUE)[[1]])
#[1] 1 2 7
或者使用str_locate
正则表达式lookbehind(在这种情况下减去1)
stringr::str_locate_all(x, "(?<=11)")[[1]][,2]-1
#[1] 1 2 7
或者正则表达式前瞻
stringr::str_locate_all(x, "(?=11)")[[1]][,1]
#[1] 1 2 7
此方法与 OP 的区别在于,使用 OP 的方法,一旦匹配成功,它就会跳过该部分并寻找下一个匹配。如果我们看另一个字符串,可以更好地解释这一点
x1 <- "11110001101"
str_locate_all(pattern = "11", x1)
#[[1]]
# start end
#[1,] 1 2
#[2,] 3 4
#[3,] 8 9
使用正则表达式查找,将有 4 个匹配项
as.integer(gregexpr("(?=11)", x1, perl = TRUE)[[1]])
#[1] 1 2 3 8
关于r - 查找连续匹配的模式索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239756/