这是一种使用 gregexpr 提取所有不同长度的重叠匹配的方法。
x<-"abaaaababaaa"
# nest in lookahead + capture group
# to get all instances of the pattern "(ab)|b"
matches<-gregexpr('(?=((ab)|b))', x, perl=TRUE)
# regmatches will reference the match.length attr. to extract the strings
# so move match length data from 'capture.length' to 'match.length' attr
attr(matches[[1]], 'match.length') <- as.vector(attr(matches[[1]], 'capture.length')[,1])
# extract substrings
regmatches(x, matches)
# [[1]]
# [1] "ab" "b" "ab" "b" "ab" "b"
诀窍是将模式包围在一个捕获组中,并将该捕获组包围在一个前瞻断言中。 gregexpr 将返回一个列表,其中包含具有属性capture.length 的起始位置,其中第一列是第一个捕获组的匹配长度的矩阵。如果将其转换为向量并将其移动到 match.length 属性中(全为零,因为整个模式都在前瞻断言中),则可以将其传递给 regmatches 以提取字符串。
正如最终结果的类型所暗示的那样,经过一些修改,这可以向量化,对于 x 是字符串列表的情况。
x<-list(s1="abaaaababaaa", s2="ab")
matches<-gregexpr('(?=((ab)|b))', x, perl=TRUE)
# make a function that replaces match.length attr with capture.length
set.match.length<-
function(x) structure(x, match.length=as.vector(attr(x, 'capture.length')[,1]))
# set match.length to capture.length for each match object
matches<-lapply(matches, set.match.length)
# extract substrings
mapply(regmatches, x, lapply(matches, list))
# $s1
# [1] "ab" "b" "ab" "b" "ab" "b"
#
# $s2
# [1] "ab" "b"