R gregexpr上的正则表达式匹配

时间:2013-01-22 04:16:46

标签: regex string r

我正在尝试计算3个连续“a”事件"aaa"的实例。

该字符串将包含较低的字母,例如"abaaaababaaa"

我尝试了以下代码。但这种行为并不是我想要的。

x<-"abaaaababaaa";
gregexpr("aaa",x);

我希望匹配返回“aaa”事件的3个实例,而不是2.

假设索引从1开始

  • 第一次出现的“aaa”是指数3.
  • 第二次出现的“aaa”是在索引4处。(这不会被捕获 gregexpr)
  • “aaa”的第三次出现在索引10处。

3 个答案:

答案 0 :(得分:6)

要捕捉重叠的匹配,您可以使用这样的前瞻:

gregexpr("a(?=aa)", x, perl=TRUE)

但是,你的匹配现在只是一个“a”,所以它可能会使这些匹配的进一步处理复杂化,特别是如果你并不总是寻找固定长度的模式。

答案 1 :(得分:1)

我知道我迟到了,但我想分享这个解决方案,

your.string <- "abaaaababaaa"
nc1 <- nchar(your.string)-1
x <- unlist(strsplit(your.string, NULL))
x2 <- c()
for (i in 1:nc1)
x2 <- c(x2, paste(x[i], x[i+1], x[i+2], sep="")) 
cat("ocurrences of <aaa> in <your.string> is,", 
    length(grep("aaa", x2)), "and they are at index", grep("aaa", x2))
> ocurrences of <aaa> in <your.string> is, 3 and they are at index 3 4 10

来自弗兰的R-help的this answer深受启发。

答案 2 :(得分:0)

这是一种使用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"