查找连续匹配的模式索引
Find the consecutively matched pattern index
我想在某个字符串中找到匹配模式的所有索引。例如,我有一个字符串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:使用包 stringr
中的 str_locate_all
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
正则表达式回顾(在这种情况下减去 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 的方法,一旦匹配完成,它就会跳过该部分并寻找下一个匹配项。如果我们看另一个 string
可以更好地解释这一点
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
我想在某个字符串中找到匹配模式的所有索引。例如,我有一个字符串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:使用包
中的stringr
str_locate_all
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
正则表达式回顾(在这种情况下减去 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 的方法,一旦匹配完成,它就会跳过该部分并寻找下一个匹配项。如果我们看另一个 string
可以更好地解释这一点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